Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

javascript - 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])

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...