【发布时间】:2013-02-03 19:16:56
【问题描述】:
我有以下主干视图。我有一个疑问。如果模型被删除,我会在取消后调用渲染(第一种方法),另一种方法是使用初始化函数,它使模型在视图内监听事件更改。(第二种方法)
谁能告诉我,一和二的区别。至于两者哪个更好。
第一种方法 var AppointmentView = Backbone.View.extend({ 模板:_.template('">' + '' + 'x'),
events: { "click a": "cancel" },
cancel: function(){
this.model.cancel();
this.render(); // rendering after cancel
},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
}
});
第二种方法
var AppointmentView = Backbone.View.extend({
template: _.template('<span class="<% if(cancelled) print("cancelled") %>">' +
'<%= title %></span>' +
'<a href="#">x</a>'),
initialize: function(){
this.model.on("change", this.render, this);
},
events: { "click a": "cancel" },
cancel: function(){
this.model.cancel();
},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
}
});
【问题讨论】:
-
取消方法对模型有什么作用?因为你不能通过调用模型本身的方法来删除模型(没有意义),或者反过来问......你想达到什么目的?模型更改后的渲染或模型从集合中删除后的渲染?
-
@Drejc,
Model#destroy是通过调用模型上的方法从集合中删除模型的方法示例。只是说。 -
因此,无论哪种方式,您都需要通过直接或间接删除模型来通知集合该模型不再存在。
标签: backbone.js