下划线bindAll:保留“this”语境
当调用 onSubmit
时,我在尝试将 uploader
保留为 this
上下文时遇到问题。有哪位 JS 高手可以帮忙吗?
uploader: {
init: function(){
var that = this;
var fileUploader = new Uploader.FileUploaderBasic({
button : $("#upload-btn")[0],
action : "/filesCollection",
onSubmit : that.onSubmit
});
_.bindAll(this, this.onSubmit); // attempting to bind 'this'
},
onSubmit: function(id, fileName){
console.log(this); // still refers to 'fileUploader' object :(
}
}
导致以下错误:
Uncaught TypeError: Cannot read property 'bind' of undefined
I am having issues attempting to preserve uploader
as the this
context when onSubmit
is called. Can any JS gurus help out?
uploader: {
init: function(){
var that = this;
var fileUploader = new Uploader.FileUploaderBasic({
button : $("#upload-btn")[0],
action : "/filesCollection",
onSubmit : that.onSubmit
});
_.bindAll(this, this.onSubmit); // attempting to bind 'this'
},
onSubmit: function(id, fileName){
console.log(this); // still refers to 'fileUploader' object :(
}
}
Results in the following error:
Uncaught TypeError: Cannot read property 'bind' of undefined
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题已解决: http://jsfiddle.net/WilsonPage/BE3Lp/41/
我发现的几件重要的事情:
_.bindAll()
。this
。this
),并且它们必须是字符串形式!this
) 然后省略任何函数名称并将对象 (this
) 作为唯一的参数,例如。_.bindAll(this)
希望这能帮助像我这样困惑的人!
Problem Solved: http://jsfiddle.net/WilsonPage/BE3Lp/41/
Several Important Things I Discovered:
_.bindAll()
must be called before the function is assigned.this
you wish to bind.this
) and they must be in string form!this
) then omit any function names and have the object (this
) as the only argument eg._.bindAll(this)
Hope this helps some confused peeps like me!
通过使用
call
或apply>,您可以为任何函数指定
this
的上下文。这应该可以解决问题(在 fileUploader 声明中):编辑:更新了 jsfiddle:http: //jsfiddle.net/WDTBV/1/
By using
call
orapply
you can specify the context forthis
for any function. This should do the trick (in the fileUploader declaration):Edit: Updated jsfiddle: http://jsfiddle.net/WDTBV/1/