需要 Underscore.js 中 _.bindAll() 函数的解释
我一直在学习一些backbone.js,并且见过很多使用 _.bindAll()
的实例。我已经阅读了整个backbone.js和underscore.js文档页面,试图了解它的作用,但我仍然对它的作用非常模糊。这是下划线的解释:
_.bindAll(对象, [*methodNames])
绑定多个方法 对象,由 methodNames 指定,以 在该对象的上下文中运行 每当它们被调用时。非常方便 用于绑定正在运行的函数 用作事件处理程序,其中 否则将被调用 这个相当没用。如果没有方法名 提供了所有对象的 函数属性将绑定到 它。
var buttonView = { 标签:'下划线', onClick : function(){ Alert('点击:' + this.label); }, onHover : function(){ console.log('悬停: ' + this.label); } }; _.bindAll(buttonView); jQuery('#underscore_button').bind('click', buttonView.onClick); =>单击按钮时, this.label 将具有正确的值...
如果您可以通过提供另一个示例或一些口头解释来提供帮助,我们将不胜感激。我尝试搜索更多教程或示例,但没有找到满足我需要的内容。大多数人似乎只知道它会自动做什么......
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:
_.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...
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不幸的是,实际的“绑定所有”功能仅适用于对象上的函数。要包含在原型上定义的函数,您需要将这些函数名称作为附加参数显式传递给
_.bindAll()
。不管怎样,你想要一个解释:基本上它允许你用一个具有相同名称和行为的函数替换一个对象上的函数,但也绑定到该对象,所以
this === theObject
即使不将其作为方法调用 (theObject.method()
)。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()
).对我来说最简单的解释如下:
The simplest explanation as for me is the next:
试试这个
try this