Javascript 需要解释 Underscore.js 的 _.bindAll() 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6582059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:22:08  来源:igfitidea点击:

need explanation of the _.bindAll() function from Underscore.js

javascriptbackbone.jsunderscore.js

提问by Nik So

I've been learning some backbone.js and I've seen plenty of instances where _.bindAll()is used. I have read through the entire backbone.js and underscore.js documentation page to try to get a sense of what it does, but I still am very fuzzy as to what it does. Here is underscore's explanation:

我一直在学习一些backbone.js,我看到了很多使用的实例_.bindAll()。我已经通读了整个backbone.js 和underscore.js 文档页面,试图了解它的作用,但我仍然对它的作用非常模糊。下面是下划线的解释:

_.bindAll(object, [*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. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless this. If no methodNames are provided, all of the object's function properties will be bound to it.

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...
_.bindAll(object, [*methodNames]) 

在对象上绑定由 methodNames 指定的许多方法,以便在调用它们时在该对象的上下文中运行。对于将用作事件处理程序的绑定函数非常方便,否则会以相当无用的 this 调用。如果未提供 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...

If you can help out here by giving another example perhaps or some verbal explanation, anything would be appreciated. I tried to search for more tutorials or examples, but nil turn up that serve what I needed. Most people seem to just know what it does automatically...

如果您可以通过提供另一个示例或一些口头解释来提供帮助,我们将不胜感激。我试图搜索更多的教程或示例,但没有找到我需要的。大多数人似乎只知道它会自动做什么......

采纳答案by ThiefMaster

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

不幸的是,实际的“全部绑定”功能仅适用于对象上的功能。要包含在原型上定义的函数,您需要将这些函数名称作为附加参数显式传递给_.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 === theObjecteven without calling it as a method (theObject.method()).

无论如何,您需要一个解释:基本上它允许您用具有相同名称和行为的函数替换对象上的函数,但也绑定到该对象,因此this === theObject即使不将其作为方法调用 ( theObject.method())。

回答by Roman Yudin

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
}

回答by wildpea

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>