Backbone Collection.add似乎不起作用

mxg2im7a  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(135)

我正在构建一个简单的to-do应用程序在 Backbone 网。我的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>

我的 Backbone.js 代码如下所示:

$(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;
});

问题很简单,由于某种原因,this.todos上的.add函数在第一次之后就不起作用了。add事件也只触发了一次。就好像集合变得不可变了。我是否错过了什么明显的东西?

nle07wnf

nle07wnf1#

该集合只是阻止您添加具有相同id的模型。如果您要添加具有不同id的模型,一切都应该正常工作。在您的情况下,如果您真的不打算自己管理id,您可以在模型示例化时忽略它们,并让backbone为您生成它们。

相关问题