2013-08-17 51 views
1

这是来自我的骨干视图。但我不断收到以下错误:骨干视图 - 如何通过多种功能传递'this'?

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) 

    }); 
}, 
+2

见(上SO和可能的几个其他问题)http://stackoverflow.com/questions/337878/var-self-this – tsiki

回答

2

在您的匿名函数(回调)this的范围代表不是由该函数创建你的观点,但原型(类)。

因此,您应该强制该功能使用特定的this上下文。

您可以使用下划线/ 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));