0

I have something like this

$ ->
  class MyView extends Backbone.View
    initialize: ->
      stuff

    $("body").on "click", ".stuff", ->
      @functionB()

    functionA: (new_date) ->
      stuff

    functionB: () =>
      stuff

  new MyView(el: $mySelector)

I want to call functionB from the event handler.
I know that I can use fat arrows, but how would I do it with _.bindAll

Robert Levy
  • 28,747
  • 6
  • 62
  • 94
LemonMan
  • 2,963
  • 8
  • 24
  • 34

2 Answers2

0

First of all, I'm guessing that $("body").on "click", ".stuff", -> is actually inside your initialize method and you just have a formatting problem. Your code doesn't make a lot of sense otherwise.

The problem you'll run into is that jQuery controls what @ (AKA this) is inside the callback function. So just binding functionB won't be sufficient because you can't get at functionB without having the right @ already.

In your specific case, none of this really matters because functionB is defined as a bound function (using =>) and you have no need for an anonymous wrapper in the event handler, just hand on the function itself:

$("body").on "click", ".stuff", @functionB

If for some reason you insist on bind an anonymous function then you'd want to use _.bind (or Function.prototype.bind) rather than _.bindAll; _.bindAll binds functions (by name) to a specific @ but you want to find a specific function (which has no name) to a specific @, see What is the difference between these Backbone/Underscore .bind() methods? for more discussion on the difference. You'd say something like:

$("body").on "click", ".stuff", _(-> @functionB()).bind(@)

# or

unbound_function = -> @functionB()
$("body").on "click", ".stuff", _.bind unbound_function, @
Community
  • 1
  • 1
mu is too short
  • 426,620
  • 70
  • 833
  • 800
0

since you are using backbone, you can either use the native syntax for binding, => or the built in underscore methods of _bind and _bindAll. they do the same thing, its just a matter of where you declare them. If you bind them at function declaration, you can then have a reference to them if you want to dispose of the event listener.

$ ->
  class MyView extends Backbone.View
    initialize: ->
      stuff

    $("body").on "click", ".stuff", @functionB
    # alternatively, inline as an anonymous function (then you can 
    # leave the declaration of functionB below as `->` )
    $("body").on "click", ".stuff", => @functionB(arguments...)

    functionA: (new_date) ->
      stuff

    functionB: () =>
      stuff
Jed Schneider
  • 14,085
  • 4
  • 35
  • 46