Reputation: 7385
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
.
Upvotes: 2
Views: 1009
Reputation: 4129
When you use on
function on an object, you are binding a callback
to an event
on that object, and the callback
must be a function, like this :
this.on("add", function() { console.log("added"); });
Upvotes: 6