我正在骨干网中构建一个简单的待办事项应用程序。我的html是:
<!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>
我的主干代码如下所示:
$(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;
});
问题很简单,由于某种原因,第一次后.add
功能不起作用。this.todos
该add
事件也只触发一次。就好像集合已成为不可变的一样。我错过了什么明显的东西吗?