我一直在学习一些backbone.js,我看到了很多使用_.bindAll()
的例子。我已经通读了整个backbone.js和underscore.js文档页面,试图了解它的作用,但我仍然对它的作用一无所知。下面是下划线的解释:
_.bindAll(object,*methodNames)
在对象上绑定由methodNames指定的许多方法,每当调用这些方法时,这些方法都将在该对象的上下文中运行。对于将要用作事件处理程序的绑定函数非常方便,否则将使用相当无用的this调用这些函数。如果没有提供methodNames,则对象的所有函数属性都将绑定到它。
var buttonView ={ label:‘下划线’,onClick : function(){ alert(' clicked:‘+ this.label);},onHover : function(){ console.log('hovering:’+ this.label);} };_.bindAll(buttonView);jQuery('#underscore_button').bind('click',buttonView.onClick);=>当点击按钮时,this.label会有正确的值...
如果你能在这里提供另一个例子或者一些口头的解释,任何事情都将不胜感激。我试着搜索更多的教程或例子,但没有找到我需要的。大多数人似乎只知道它会自动地做什么。
发布于 2011-07-05 19:46:48
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>
不幸的是,实际的“全部绑定”功能只适用于对象上的函数。要包含在原型上定义的函数,需要显式地将这些函数名作为附加参数传递给_.bindAll()
。
无论如何,你想要一个解释:基本上,它允许你用一个具有相同名称和行为的函数替换一个对象上的函数,但也绑定到该对象,所以即使不将其作为方法(theObject.method()
)调用,也可以使用this === theObject
。
发布于 2013-08-06 23:28:08
对我来说,最简单的解释是:
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
}
发布于 2013-02-21 14:32:45
尝尝这个
<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>
https://stackoverflow.com/questions/6582059
复制相似问题