2013-08-17 94 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));