36
I am a Backbone.js newbie. I was just playing around with it. I would like to know whether the model is related with the View. In the provided todos example, I see in the addOne method, a new View is created and associated with the newly created model and appended.
window.AppView = Backbone.View.extend({
// view code
addOne: function(todo) {
var view = new TodoView({model: todo});
this.$("#todo-list").append(view.render().el);
}
}
When I tried to do a similar thing, I got an error saying "bind method cannot be found on undefined".
window.TodoView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render', 'close');
this.model.bind('change', this.render); // I got the error at this place.
this.model.view = this;
}
});
In order to solve this, I got to pass the newly created model as a param to the view constructor and I got to do this.model = task inorder to associate it.
window.TodoView = Backbone.View.extend({
initialize: function(task) {
_.bindAll(this, 'render', 'close');
this.model = task
this.model.bind('change', this.render);// now there is no error
this.model.view = this;
}
});
window.AppView = Backbone.View.extend({
insertTask:function(){
var newTask, newTaskView;
newTask = new Task(JSON.parse(xhr));
Tasks.create(newTask);
newTaskView = new TaskView({ model: newTask });
$("#todo_list").append(newTaskView.render().el);
this.input.val('');
}
});
But the todos example, do not have something like that. How is the new model associated with the new view implicitly in the todos example?
Thanks