0
votes

I have the following backbone view. I had a doubt. In case if a model is deleted, i call the render after cancel(First Approach), the other way of doing it would be to have an initialize function, which renders the model listening to the event changes, inside the views.(Second Approach)

Could someone please let me know, the difference between one and two. As to which of the two is better.

First Approach 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()));
  }
});

Second Approach

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()));
  }
});
1
What does you cancel method do to the model? As you can't delete a model by calling a method on the model itself (makes no sense), or asked the other way around ... what are you trying to achieve? A render after the model has changed or a render after the model was removed from a collection?Drejc
@Drejc, Model#destroy is an example of a method that removes a model from a collection by calling a method on the model. Just saying.jevakallio
So either way you need to inform the collection that the model is no longer present, by directly or indirectly removing it.Drejc

1 Answers

0
votes

I would define a custom cancelled event, trigger that from your cancel method, and bind to that event in the view.

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);
  }
});

This way your view will re-render, even if the model is cancelled from elsewhere than the view itself, but you still get the specific behavior or only re-rendering upon cancel, and not on every change.