суббота, 29 ноября 2014 г.

Как не вязать вью на модель в new Backbone.js

В новом бекбоне появилось встроенное решение отвязки модели от разрешенного дома вьюхи.
Было:

  
var AppointmentView = Backbone.View.extend({
  template: _.template("<%= title %>"),
  initialize: function(){
    this.model.on('change:title', this.changedTitle, this);
  },
  render: function(){
    this.$el.html(this.template(this.model.attributes));
  },
  changedTitle: function(model, value, options){
    this.$('span').html(value);

    if (options.highlight !== false){
      this.$el.effect('highlight', {}, 1000); 
    }
  },
  remove: function() {
    Backbone.View.prototype.remove.apply(this, arguments);
    this.model.off(null, null, this);
  }
});

var appointmentView = new AppointmentView({model: someModel});

appointmentView.remove();


Стало(Added in Backbone 0.9.9):
var AppointmentView = Backbone.View.extend({
  template: _.template("<%= title %>"),
  initialize: function(){
    this.listenTo(this.model, 'change:title', this.changedTitle);
  },
  render: function(){
    this.$el.html(this.template(this.model.attributes));
  },
  changedTitle: function(model, value, options){
    this.$('span').html(value);

    if (options.highlight !== false){
      this.$el.effect('highlight', {}, 1000); 
    }
  }
});


var appointmentView = new AppointmentView({model: someModel});

appointmentView.remove();// автоматически вызовет appointmentView.stopListening();

Комментариев нет:

Отправить комментарий