[英]Backbone View - How can I pass 'this' through multiple functions?
这是从我的骨干网视图来看的。 但是我一直收到以下错误:
Uncaught TypeError: Cannot call method 'add' of undefined
。
如何保持此状态,以便可以向收藏夹添加新模型?
addGroupModal: function() {
$('#add-group-modal').modal('show');
// Manual Event Listener for Submit Button
$("#add-group-submit-button").click(function(){
var newGroup = new KAC.Models.KeepAContactGroup({ name: '123', list_order: '2' });
console.log(newGroup)
newGroup.save();
this.collection.add(newGroup)
});
},
在匿名函数(回调)的范围内, this
不表示您的视图,而是表示该函数创建的原型(类)。
因此,您应强制该函数使用特定的this
上下文。
您可以使用_.bind()
/ LoDash _.bind()
方法
或本机Function.prototype.bind() (适用于所有主流浏览器和IE> 8)。
addGroupModal: function() {
$('#add-group-modal').modal('show');
// Manual Event Listener for Submit Button
$("#add-group-submit-button").click(_.bind(function() {
var newGroup = new KAC.Models.KeepAContactGroup({
name: '123',
list_order: '2'
});
console.log(newGroup);
newGroup.save();
this.collection.add(newGroup);
}, this));
}
本机绑定:
$("#add-group-submit-button").click(function() {
// ...
}.bind(this));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.