下面是在页面上列出一个列表的代码,它们是2个用于删除和通过提示框更新的功能,当我点击更新时,视图确实在console.log中更新但是没有刷新DOM。
(function(){
window.App = {
Models: {},
Collections:{},
Views: {}
};
window.template = function(id) {
return _.template($('#'+id).html());
};
App.Models.Task = Backbone.Model.extend({
validate: function(attrs){
if (! attrs.title){
return 'A task requires a valid title';
}
}
});
App.Collections.Task = Backbone.Collection.extend({
model: App.Models.Task
});
App.Views.Tasks = Backbone.View.extend({
tagName: 'ul',
render: function(){
this.collection.each(this.addOne,this);
return this;
},
addOne: function(task){
var taskView = new App.Views.Task({model:task});
this.$el.append(taskView.render().el);
}
});
App.Views.Task = Backbone.View.extend({
tagName: 'li',
template: template('taskTemplate'),
initalize: function(){
this.model.on('change:title',this.render,this);
this.model.on('destory',this.remove,this);
},
events: {
'click .edit': 'editTask',
'click .delete': 'destroy'
},
editTask: function(){
var newTaskTitle = prompt('what is the new text for the task ?',this.model.get('title'));
if(!newTaskTitle)return;
this.model.set('title',newTaskTitle);
},
destroy: function(){
this.model.destroy();
},
remove:function(){
this.$el.remove();
},
render: function(){
var template = this.template(this.model.toJSON());
this.$el.html(template);
return this;
}
});
window.taskCollection = new App.Collections.Task([
{
title: 'Go to the store',
priority:3
},
{
title: 'Go to gym',
priority:2
},
{
title: 'Learn backbone',
priority:1
}
]);
var taskView = new App.Views.Tasks({collection:taskCollection});
$('.tasks').html(taskView.render().el);
})();
答案 0 :(得分:0)
好看,有点想通了,
我按如下方式修改了代码,
editTask: function(){
var newTaskTitle = prompt('what is the new text for the task ?',this.model.get('title'));
if(!newTaskTitle)return;
this.model.set('title',newTaskTitle);
**this.render();**
}
此代码用于销毁
destroy: function(){
this.model.destroy();
this.$el.remove();
},
有人可以告诉为什么this.reder无效吗? (我在youtube的教程中看到了这一点) - this.model.on('change:title',this.render,this);