HOW TO HANDLE INITIALIZING AND RENDERING SUBVIEWS IN BACKBONE.JS?

How to handle initializing and rendering subviews in Backbone.js?

  • The view’s container element (affectionately known as its el) swaps out all of its html for new html, probably fetched from a template. The problem is in the child view.

There are several ways to handle this situation

1. Don’t Re-Render the Parent View

The simplest is to design a parent view that doesn’t require re-rendering. It has static content and serves as a container of child views. The child view container elements are never re-rendered, so they never go stale.

2. Reassign the Child View’s Element

Another more practical approach is to reassign the child view’s container once the parent view renders. Your view can now re-render appropriately, but its events will still be broken, as they are still stale. This second piece can be fixed with a call to delegate Events.

Example
Example.ParentView= Backbone.View.extend({
childView:new Example.ChildView(),
render:function(){
this.$el.html(this.template(this.model.
toJSON()));
this.childView.$el
=this.$(‘#child-view-container’);
this.childView.render();
this.childView.delegateEvents();
}
});

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>