开发者

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

开发者 https://www.devze.com 2023-03-28 09:27 出处:网络
window.So开发者_StackOverflow社区meView = Backbone.View.extrend({ initialize1: function() { _.bindAll(this, \'render\');
window.So开发者_StackOverflow社区meView = 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])


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消