I am building a simple to-do application in backbone. my html is:
<!DOCTYPE html>
<html>
<head>
<title>back bone</title>
<script src="js/lib/jquery.js"></script>
<script src="js/lib/underscore.js"></script>
<script src="js/lib/backbone.js"></script>
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css"/>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<body>
<h2>Total Things Todo: <div id="no-todo"> 0 </div></h2>
<ul id="todo-list" class="unstyled">
</ul>
<div>
<button class="btn" id="add-todo"><i class="icon-plus"></i>Add Todo</button>
</div>
<script src="js/script.js"></script>
</body>
</html>
and my backbone code looks like this:
$(document).ready(function(){
var Todo = Backbone.Model.extend({
id: 0,
text:null,
completed: false
});
var Todos = Backbone.Collection.extend({
model:Todo,
initialize: function(models, options) {
this.on("add",options.view.addTodoLi);
}
});
var AppView = Backbone.View.extend({
el: $("body"),
initialize: function() {
this.todos = new Todos(null,//[{id: 0,completed: false,text: "helo"},{id: 1,completed: false,text: "bye"}],
{view: this });
},
events: {
"click #add-todo": "addTodo"
},
addTodo: function() {
var todo_name = prompt("What do you have to do?");
var todo_model = new Todo({id: 0,completed: false,text: todo_name});
this.todos.add(todo_model);
console.log("todos",this.todos.toJSON(),
todo_name,todo_model.toJSON());
},
addTodoLi: function(model){
$("#todo-list").append("<li><div class='done-false'><input type='checkbox'/>"+model.get("text")+"</div></li>");
}
});
var appview = new AppView;
});
The problem is simple, for some reason .add
function on the this.todos
is not working after the first time. The add
event is also triggered just once .It is as if the collection has become immutable. Have I missed something obvious?
The collection simply prevents you from adding models that have the same id
. If you were to add models with different id
s everything should work just fine. In your case if you really don't intend to manage the ids by yourself you could omit them upon model instantiation and have backbone generate them for you.