我一直在学习backbone.js,看到很多地方都用到了_.bindAll()
,我已经阅读过整个backbone.js和underscore.js的文档页面,试图理解它的作用,但我仍然不太清楚。这是underscore的解释:
如果你能提供另一个示例或一些口头解释,将不胜感激。我尝试搜索更多的教程或示例,但没有符合我的需求的结果。大多数人似乎都自动知道它的作用..._.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...