骨干视图 - 如何通过多个功能传递'this'?

时间:2013-08-17 18:18:05

标签: javascript jquery backbone.js

这是我的Backbone View。但我不断收到以下错误:

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)

  });
},

1 个答案:

答案 0 :(得分:2)

在匿名函数的范围内(回调)this表示不是您的视图,而是由该函数创建的原型(类)。

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

您可以使用Underscore / 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));
相关问题