需要从Underscore.js中解释_.bindAll()函数

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

 _.bindAll(object, [*methodNames]) 

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

如果你可以通过另外一个例子或者口头的解释来帮助你,那么任何事情都将不胜感激。 我试图寻找更多的教程或例子,但没有出现,我所需要的服务。 大多数人似乎只是知道它是什么自动执行的…

 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> 

下面是我最简单的解释:

 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 } 

尝试这个

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