0

我有以下主干视图。我有一个疑问。如果模型被删除,我会在取消后调用渲染(第一种方法),另一种方法是使用初始化函数,它使模型在视图内监听事件更改。(第二种方法)

有人可以告诉我,一和二的区别。至于两者哪个更好。

第一种方法 var AppointmentView = Backbone.View.extend({ template: _.template('">' + '<%= title %>' + '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()));
  }
});
4

1 回答 1

0

我会定义一个自定义cancelled事件,从您的cancel方法中触发它,然后在视图中绑定到该事件。

var Appointment = Backbone.Model.extend({
  cancel: function() {
    //cancellation code...
    this.trigger('cancelled', this);
  }
});

var AppointmentView = Backbone.Model.extend({
  initialize: function() {
    this.listenTo(this.model, 'cancelled', this.render);
  }
});

这样,即使模型从视图本身以外的其他地方取消,您的视图也会重新渲染,但您仍然会获得特定行为或仅在 上重新渲染cancel,而不是在每次更改时重新渲染。

于 2013-02-19T09:40:55.753 回答