Search code examples
javascriptbackbone.jsbackbone-eventsbackgrid

How to call render method of a cell view from the editor view upon change event?


I have the backbone view like

var EditorView = Backbone.View.extend({
  //.....
});

var CellView = Backbone.View.extend({
  editor: EditorView
  initialize: function (optionValues,multiple) {
  //....
  this.listenTo(this.editor,'change',this.render);
 }
  //.....
});

But the above only listen to event only once, Not twice.

How should i use listenTo function so that view always listens to the model's events.


Solution

  • You are listening on an event from a constructor of a view. EditorView is a constructor function and not an instance of the view.

    You should either use global messenging to communicate between views:

    var EditorView = Backbone.View.extend({
      //.....
      change : function() {
        Backbone.trigger('editor:change');
      }
    });
    
    var CellView = Backbone.View.extend({
      initialize: function (optionValues,multiple) {
      this.listenTo(Backbone,'editor:change',this.render);
     }
    });
    

    Or pass the editor's instance in the creation of the cell view:

    var CellView = Backbon.View.extend({
      initialize: function( options ) {
        this.editor = options.editor;
        this.listenTo( this.editor, 'change', this.render );
      }
    });
    

    I think the global messenging style is clearer and offers more flexibility.