2014-02-07 120 views
1

真的很基本的问题,但我似乎无法弄清楚为什么我无法将方法绑定到集合上的重置事件。绑定功能骨干收集重置

HealthcheckList = Backbone.Collection.extend({ 

    model: Healthcheck, 
    url: "/corsettiServices/rest/healthcheck/sort", 

    initialize: function() { 
     _.bindAll(this, "fetchSuccess", "addAll"); 
     console.log("Initializing view"); 
     this.on('reset', addAll); 
     this.fetch({data: {type:'all'}, processData:true, success: this.fetchSuccess, reset: true}); 
    }, 

    addAll: function(m, options) { 
     alert("adding"); 
    }, 

    fetchSuccess: function(m, response) { 
     alert("success"); 
     console.log(m); 
     m.each(function(h) { 
      if (h.get("start")!=null) { 
       $('#statusTable > tbody:last').append('<tr><td>' + h.get("start") + '</td><td>' + h.get("type") + '</td><td>' + h.get("status") + '</td></tr>'); 
      } 
     }) 
    } 
}) 

这会引发一个错误:Uncaught ReferenceError:addAll没有定义。删除“重置”事件的绑定会使数据获取和代码正常工作,但是我希望每次重置集合时都要执行更多处理。我错过了如何在骨干集合中定义函数?

回答

1
this.on("reset", this.addAll); 

你想要小心范围。初始化函数将被绑定到“this”,这将成为在某个时刻实例化的新对象。但是,在初始化函数的范围内,addAll是未定义的,因为您正在将此项写入“this”尚不存在的范围内。最终,addAll属性将被绑定到“this”,但在这里,addAll是您传入的新对象的一个​​属性,它指向一个匿名函数。

+0

自从他做了'_.bindAll'之后,甚至不需要传递上下文,只需要使用'this.addAll'而不是'addAll'。 – Ford

+0

正确,并在使用上下文||这个。所以,它会默认这个。我更新了答案并提供了解释。 –

+0

谢谢,我以为我尝试过,但显然不是。欣赏功能范围的细节。 – Chris