以下是我的一些代码:
Tasks = Backbone.Collection.extend({
//This is our Task collection and holds our Task models
initialize: function (models, options) {
console.log(options);
this.bind("add", options.view.addTaskListeners);
console.log(this.bind("add", options.view.addTaskListeners));
//Listen for new additions to the collection.
}
});
AppView = Backbone.View.extend({
el: $("body"),
initialize: function () {
this.tasks = new Tasks( null, { view: this });
// Create a task collection when the view is initialized.
// Pass it a reference to this view to create a connection between the two
},
events: {
"click #add-task": "showPrompt",
},
showPrompt: function () {
debugger;
var task_name = prompt("What is your task");
var task_time = prompt("How Long will it take");
var task_model = new Task({ name: task_name, time: task_time });
//Add a new task model to our friend collection
this.tasks.add( task_model, task_time );
},
addTaskListeners: function (model) {
//The parameter passed is a reference to the model that was added
$("#task-list").append("<li>" + model.get('name') + "</li>");
//Use .get to receive attributes of the model
}
});
在我的视图中,我有一个showPrompt函数,可以为Collection添加模型。
this.tasks.add( task_model, task_time );
我的集合有某种形式的事件监听器,代码看起来像这样。
this.bind("add", options.view.addTaskListeners);
我相信这些代码段是相互通话的。我相信this.bind正在侦听add事件。我不明白参数'options'是什么以及我们为什么要调用options.view.addTaskListeners
答案 0 :(得分:1)
我认为正确的方法是不将视图对象传递给集合,而是添加如下的侦听器:
AppView = Backbone.View.extend({
el: $("body"),
initialize: function () {
this.collection = new Tasks();
this.listenTo(this.collection, 'add', this.addTaskListeners);
},
events: {
"click #add-task": "showPrompt",
},
....
这样,当add
事件被触发时,它将运行addTAskListeners
。
因此,为了将新模型添加到集合中,我会这样做:
showPrompt: function () {
debugger;
var task_name = prompt("What is your task");
var task_time = prompt("How Long will it take");
this.collection.add({ name: task_name, time: task_time }) //you could use .create
...
},
您可以从集合中访问模型,因此您不需要自己实例化模型。