1

After about a year I'm getting re-acquainted with my old friend backbone. Working through this tutorial I'm puzzling over a couple of things. Namely that the view's initialize uses an underscore bindAll method to scope "this" to the render method:

var CountryView = Backbone.View.extend({
    tagName: 'option',
    initialize: function(){
        _.bindAll(this, 'render');
    },
    render: function(){
        this.$el.attr('value', this.model.get('id')).html(this.model.get('name'));
        return this;
    }
});

Here's a trivial js fiddle I'm working with that works. The line in question is line 13: http://jsfiddle.net/wrGX5/1/

From reading the documentation, it looks like the only difference between _.bind and _.bindAll is that bindAll will bind to multiple methods. If that's the case, why does _.bind(this, 'render') not do the same thing? line 13 of this fiddle: http://jsfiddle.net/4t3AX/1/ Is there something fundamentally different about the way _.bind it works other than the number of methods it will scope?

Side question: can you highlight specific lines in jsfiddle?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
rakitin
  • 1,943
  • 6
  • 25
  • 51
  • 3
    Short answer: `_.bind` returns a bound function, `_.bindAll` can bind them in-place. See the answers to the duplicate for details. – mu is too short Mar 19 '14 at 15:42

1 Answers1

2

This doesn't really answer your question exactly, but since your examples are already using backbone's event functions, why use underscore's?

Brief rundown:

"On". Will bind something to any event on your model. You'd use...

this.model.on("all", this.render, this);

The "all" says to listen to every model event. The 3rd argument is for passing the context and is optional.

When you bind to "all", the function you call is passed the event name as the first argument. An example would be something like this:

render: function(eventType){
    if(eventType === "change:name"){
        this.$el.attr('value', this.model.get('id')).html(this.model.get('name'));
    }
    return this;
}

Alternatively (and probably better) you can use "listenTo". To keep all of the bindings nicely tied to the view. This has a lot of advantages in memory management (tearing down the view and not leaving any orphaned events). Your view's initialize would look something like:

initialize: function(){
    this.listenTo(this.model, "all", this.render);
}
D_Naish
  • 543
  • 4
  • 20