I have created a simple Todo application on JS Fiddle to learn Backbone.JS. I have a TodosModuleView that wraps a form and TodosView which renders the Collection of Todos
window.TodosModuleView = Backbone.View.extend({
tagName: 'section',
id: 'todoModule',
events: {
'keypress #frmTodo input[type=text]': 'addTodo'
},
initialize: function() {
_.bindAll(this, 'render',
'addTodo');
this.collection.bind('reset', this.render);
this.template = _.template($('#todosModuleTmpl').html()); },
render: function() {
console.log('rendering...');
var todosView = new TodosView({ collection: this.collection });
this.$el.html(this.template({}));
this.$el.append(todosView.render().el);
return this;
},
addTodo: function(e) {
if (e.keyCode !== 13)
return;
var todo = new Todo({ title: this.$('input[name=todo]').val() });
this.collection.add(todo);
console.log('added!');
return false;
}
});
When I add a todo, I can see it added to the collection, but it does not appear to trigger render(). Also since I am using a Local Storage store, I’d expect that my newly added Todos should be persisted and rendered on next refresh, but that does not appear to happen. Looking at the Chrome’s developer toolbar, I don’t see anything in Local Storage
UPDATE
1st Problem solved with @mashingan’s answer: use add instead of reset event. Now whats wrong with my Local Storage?
window.Todos = Backbone.Collection.extend({
model: Todo,
localStorage: new Backbone.LocalStorage('todos')
});
Could it be that variables are passed by value instead of reference as I’d expect? I have a TodosModuleView that uses TodosView to render the todo list, maybe I am doing it the wrong way?
Your LocalStorage isn’t working because you’re not saving anything. This:
simply creates a new model and adds it to the collection, there is no hidden
todo.save()call in there so the newTododoesn’t get saved. You’d have to save it yourself:You could also save everything in the collection with:
That will call
saveon each model in the collection. This might make sense for LocalStorage but not so much sense if you’re persisting to a remote server.If you do this:
Then you won’t get anything in your
pancakesdatabase, but if you addc.invoke('save')at the end:You will get a couple of good movies saved.
Demo: http://jsfiddle.net/ambiguous/ZV86g/