这些 Backbone/Underscore .bind() 方法有什么区别? [英] What is the difference between these Backbone/Underscore .bind() methods?

查看:22
本文介绍了这些 Backbone/Underscore .bind() 方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);
    },
});

在一些 SO 成员的帮助下,我能够让我的测试项目使用绑定方法 initialize1 和 initialize2;我不明白为什么 initialize3 不起作用?

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?

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

推荐答案

主要有以下三个区别;_.bind 一次只适用于一种方法,允许柯里化,并且返回strong> 绑定函数(这也意味着您可以在匿名函数上使用 _.bind):

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

函数绑定到对象,这意味着每当调用该函数时,this的值都将是对象.或者,将参数绑定到函数以预填充它们,也称为柯里化.

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.

_.bindAll 一次绑定多个 named 方法,不允许柯里化,并就地绑定它们:

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

对象上绑定多个由methodNames指定的方法,以便在调用它们时在该对象的上下文中运行.

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');

但是没有与此等效的 bindAll:

But there is no bindAll equivalent to this:

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

这使得 f()o.m1('pancakes') 相同(这是 咖喱).

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

所以,当你这样说时:

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

您将方法 render 绑定到具有与当前 this 匹配的 this 然后绑定 this.renderthis.model 上的更改事件.

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.

当你这样说时:

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

不起作用,因为您丢弃了 _.bind 的返回值(即丢弃了绑定函数).

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

这篇关于这些 Backbone/Underscore .bind() 方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆