Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these Backbone/Underscore .bind() methods?

window.SomeView = Backbone.View.extrend({
    initialize1: function() {
        _.bindAll(this, 'render');
        this.model.bind('change', this.render);
    },

    initialize2: function() {
        this.model.bind('change', _.bind(this.render, this));
    },

    initialize3: function() {
        _.bind(this.render, this);
        this.model.bind('change', this.render);
    },
});

With help from some SO members, I was able to get my test project working with binding methods initialize1 and initialize2; what I don't understand is why initialize3 doesn't work?

documentation: _.bind(function, object, [*arguments])

like image 875
rkw Avatar asked Aug 17 '11 03:08

rkw


1 Answers

There are three main differences; _.bind only works on one method at a time, allows currying, and returns the bound function (this also means that you can use _.bind on an anonymous function):

Bind a function to an object, meaning that whenever the function is called, the value of this will be the object. Optionally, bind arguments to the function to pre-fill them, also known as currying.

whereas _.bindAll binds many named methods at once, doesn't allow currying, and binds the them in-place:

Binds a number of methods on the object, specified by methodNames, to be run in the context of that object whenever they are invoked.

So these two chunks of code are roughly equivalent:

// Bind methods (not names) one a time.
o.m1 = _.bind(o.m1, o);
o.m2 = _.bind(o.m2, o);

// Bind several named methods at once.
_.bindAll(o, 'm1', 'm2');

But there is no bindAll equivalent to this:

f = _.bind(o, o.m1, 'pancakes');

That makes f() the same as o.m1('pancakes') (this is currying).


So, when you say this:

_.bindAll(this, 'render');
this.model.bind('change', this.render);

You're binding the method render to have a this that matches the current this and then you're binding this.render to the change event on this.model.

When you say this:

this.model.bind('change', _.bind(this.render, this));

You're doing the same thing. And this:

_.bind(this.render, this);
this.model.bind('change', this.render);

doesn't work because you're throwing away the return value of _.bind (i.e. you throw away the bound function).

like image 134
mu is too short Avatar answered Oct 25 '22 23:10

mu is too short