需要了解 Underscore.js 中的 _. bindAll()函数

我已经学习了一些 backbone.js,并且看到了大量使用 _.bindAll()的实例。我已经阅读了所有的 backbone.js 和 underscore.js 文档页面,试图了解它的功能,但是对于它的功能我还是很模糊。以下是强调的解释:

_.bindAll(object, [*methodNames])

上绑定许多方法 由 methodNames 指定的 在该对象的上下文中运行 随时都可以使用,非常方便 用于绑定正在运行的函数 用作事件处理程序,其中 否则将使用 如果没有方法名,这个就相当没用了 所有对象的 函数属性将绑定到 它。

var buttonView = {
label   : 'underscore',
onClick : function(){ alert('clicked: ' + this.label); },
onHover : function(){ console.log('hovering: ' + this.label); }
};


_.bindAll(buttonView);


jQuery('#underscore_button').bind('click', buttonView.onClick);
=> When the button is clicked, this.label will have the correct value...

如果你能给出另一个例子或者一些口头解释来帮助我们,我们将不胜感激。我试图搜索更多的教程或示例,但是没有找到能够满足我需要的。大多数人似乎只知道它会自动..。

27618 次浏览

var Cow = function(name) {
this.name = name;
}
Cow.prototype.moo = function() {
document.getElementById('output').innerHTML += this.name + ' moos' + '<br>';
}


var cow1 = new Cow('alice');
var cow2 = new Cow('bob');


cow1.moo(); // alice moos
cow2.moo(); // bob moos


var func = cow1.moo;
func(); // not what you expect since the function is called with this===window
_.bindAll(cow1, 'moo');
func = cow1.moo;
func(); // alice moos
<div id="output" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Unfortunately the actual "bind all" functionality only works on functions right on the object. To include a function that is defined on the prototype you need to pass those function names explicitely as additional arguments to _.bindAll().

Anyway, you wanted an explanation: Basically it allows you to replace a function on an object with a function that has the same name and behaviour, but is also bound to that object, so this === theObject even without calling it as a method (theObject.method()).

try this

<input type="button" value="submit" id="underscore_button"/>


<script>
var buttonView = {
id     : 'underscore',
onClick: function () {console.log('clicked: ' + this.id)},
onHover: function () {console.log('hovering: ' + this.id)}
}
_.bindAll(buttonView, 'onClick')
$('#underscore_button').click(buttonView.onClick)
$('#underscore_button').hover(buttonView.onHover)
</script>

The simplest explanation as for me is the next:

initialize:function () { //backbone initialize function
this.model.on("change",this.render); //doesn't work because of the wrong context - in such a way we are searching for a render method in the window object
this.model.on("change",this.render,this); //works fine
//or
_.bindAll(this,'render');
this.model.on("change",this.render); //now works fine
//after  _.bindAll we can use short callback names in model event bindings
}