2013-07-10 169 views
1

我初始化查看:骨干事件

notifications = new tvr.notifications.Collection 
notifications.fetch() 
new tvr.notifications.View collection:notifications 

林加入 “通知”,以骨干集合:

notifications = new tvr.notifications.Collection 
notifications.fetch() 
notifications.create html:this_notification 

notifications.coffee

class Notifiction extends Backbone.Model 
    class Notifictions extends Backbone.Collection 
     model = Notifiction 
     localStorage: new Backbone.LocalStorage 'tvr.notifications' 


    class NotificationView extends Backbone.View 
     initialize: -> 
      @listenTo @collection, "add", @update 

     update: -> 
      alert "update" 

    namespace 'tvr.notifications', (exports) -> 
     exports.Model = Notifiction 
     exports.Collection = Notifictions 
     exports.View = NotificationView 

这个事件从不被调用,我可以看到集合中创建的对象。

我只想知道何时添加新的或从集合中删除了新的,因此我可以更新HTML中的徽章编号。

回答

1

您正试图将"Add"事件绑定到函数调用,这是不可能的。您需要将事件绑定到函数引用,并且Backbone的事件机制将调用您代表的引用的函数。没有使用alert,这里是一个差异的例子(在JavaScript中)。

函数调用

var myFunc = function() { 
    alert("happy days"); 
} 

非法

notifications.on("add", myFunc()); 

法律

notifications.on("add", myFunc); 

所以你可以看到在你的例子中,当你使用on绑定它时,你试图调用alert函数并传递一个参数"happy days"。这是不允许的。

但是,如果您编写了一个无参数函数来包装您想调用的代码(如上面的myFunc示例中所示),并将其分配给变量或其他对象,则可以将该事件绑定到该函数的引用。这应该像你期待的那样行事。

最后,您应该使用listenTo绑定事件,而不是on。这是因为在SO上已经讨论过的原因。为了进一步的参考阅读以下内容:

Difference between ListenTo and on

Backbone js .listenTo vs .on

+0

我照你解释,但是这是行不通的。我更新了我的问题 – Harry

+0

您可能需要'_.bindAll(this)'作为'initialize'函数的第一行。另外,我看不到任何证据表明您正在为'Notifictions'集合添加模型。你在你的例子中甚至没有对它的引用,因为你在'listenTo'函数中'new'。那么你怎么能为它添加模型呢? – dcarson

+0

它在问题中,第1行和第2行。生病尝试bindAll – Harry