1

I want to render a view and it's child views without losing any bound events. Right now I am rendering the main view once, and then appending its child views to an element. When the parent view renders again it wipes out the el the child views were bound to.

Heres what I have now:

render: function() {     
    var html = this.template({model:this.model.toJSON(), otherModel:window.otherModel.toJSON()});

    this.$el.html(html);
    this.openList();
}

OpenList: function(){
    if(typeof(this.ListView)=="undefined"){
        this.ListView = new App.ListView({el:this.$("#ListView-tab"),collection:this.model.list});
    }
    this.ListView.collection.fetch();
}

I've read about a couple of approaches to fixing this:

a) fill-in rendering

this option would put the initial render in initialize and then in the render function add in the information using jquery

  initialize: function() {
      var html = this.template({model:this.model.toJSON(), otherModel:window.otherModel.toJSON()});

}

 render: function() {     
    this.$('.title').text(this.model.get('title'));
    this.$('.date').text(this.model.get('date'));

}

b) Detaching and delegating events

detach() the child el, re appending and delegateEvents() the view each time we render the parent view

render: function() {
    if(typeof(this.ListView)!="undefined"){
        this.ListView.$el.detach
    }     
    var html = this.template({model:this.model.toJSON(), otherModel:window.otherModel.toJSON()});

    this.$el.html(html);
    this.openList();
}

OpenList: function(){
    if(typeof(this.ListView)=="undefined"){
        this.ListView = new App.ListView({collection:this.model.list});
    }
    if(this.ListView.$el.parent().length)this.$("#ListView-tab").append(this.ListView.el); //if not already appended
    this.ListView.collection.fetch();
    this.ListView.delegateEvents();
}

c) the final option would be to leave most of my code as is and simply put the following code in render of the parent view

if(typeof(this.ListView)!="undefined"){
    this.ListView=undefined;
}

this would invalidate the child view and recreate it every time the main view renders.

Are there any problems with the methods i've posted? I'm leaning towards option c) since its the simplest way to make sure everything is going to get recreated and have its events working.

  • Duplicated? http://stackoverflow.com/questions/12028835/backbone-event-lost-in-re-render – fguillen Aug 22 '12 at 16:08
  • @fguillen thanks, that covers most of my question. I guess the only reason to avoid c) is to avoid rendering the entire page when the subviews don't need to be updated? –  Aug 22 '12 at 17:06

0 Answers0