简体   繁体   中英

Backbone Collection 'add' event not firing

I've got an event listener in my Collection which listens for the 'add' event, which only seems to fire when the sample data I add in my router is added, but not when I add more models in my view, the code for both is below:

Collection:

Application.Collection.extend({
  name: "todos/todos",
  initialize: function() {
    this.on("add", console.log("added"));
  },
  url: "/todo-application/todos"
});

Router (this fires an event):

collection = new Application.Collections["todos/todos"]();
var m = new Application.Model({
    title: 'Finish screencast',
    done: true
});
collection.add(m);

View (this doesn't fire an event):

Application.View.extend({
  name: "todos/index",
  events: {
    "submit form": function(event) {
        event.preventDefault();
        var attrs = this.serialize();
        this.collection.add(attrs);
        this.$('input[name=title]').val('');
    }
  }
});

The collection.add in the view definitely works, as the model is added to the collection and displayed on screen , yet the collection only gives me a console.log() on the initial pageload when the sample data is added...

EDIT:

According to my Backbone Chrome extension the event is indeed firing, but for some reason this event binding isn't working, and I have tried using this.listenTo instead of .on .

当在对象上使用on函数时,您callback绑定到该对象上的event ,并且该callback必须是一个函数,如下所示:

this.on("add", function() { console.log("added"); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM