2

I find myself writing this on multiple occasions:

{ someJQueryCallback: ->
    keepGoing = true
    $(someSelector).each ->
      unless someCondition($(@))
        keepGoing = false
        return false
    return false unless keepGoing
    moreStuff()
}

Of course, the first time, I made the rookie mistake everyone makes:

{ someJQueryCallback: ->
    $(someSelector).each -> return false unless someCondition($(@))
    moreStuff()
}

Ah, the perils of pretty syntax for functions. As a rookie, I forgot that in that scope, return would exit from each and not from someJQueryCallback. But really, even though I'm "enlightened" now, this is still the code I want to write. I want to somehow specify "pop up the stack until you've returned from someJQueryCallback." It's annoying to initialize and set and check a bool flag. It adds cruft. Is there an idiomatic way to return higher up the call stack in this way?

Dan Burton
  • 53,238
  • 27
  • 117
  • 198
  • possible duplicate of [returning outer function from inner function](http://stackoverflow.com/questions/16991597/returning-outer-function-from-inner-function) – Barmar Sep 14 '13 at 01:27
  • In this case, I am using a JQuery looping operation over a collection of arbitrary length, which should not be unrolled into a series of if statements, as in that possible duplicate. – Dan Burton Sep 14 '13 at 02:01
  • Here's a better duplicate, but it's too late for me to change the close-vote to point to it: http://stackoverflow.com/questions/15615342/how-to-exit-escape-a-function-from-for-loop-inside-of-it – Barmar Sep 14 '13 at 02:38

1 Answers1

1

I don't use coffeescript so this may not be perfect, but hopefully it gives you an idea:

{ someJQueryCallback: ->
    try
      $(someSelector).each ->
          throw new Error("STOP!") unless someCondition($(@))
        moreStuff()
    catch error
      return false;
}
grandinero
  • 1,155
  • 11
  • 18