Skip to content

Instantly share code, notes, and snippets.

@tbcorr
Created March 7, 2016 16:17
Show Gist options
  • Save tbcorr/7bbd776cf058d2b8f122 to your computer and use it in GitHub Desktop.
Save tbcorr/7bbd776cf058d2b8f122 to your computer and use it in GitHub Desktop.
A base Backbone.js View for Composite Views
// based very heavily on http://ianstormtaylor.com/rendering-views-in-backbonejs-isnt-always-simple/
CompositeView = Backbone.View.extend({
// assuming an inline underscrore template
template: _.template(jQuery('#template-composite-view').html())
initialize: function(){
this.children = [];
},
addChild: function(view){
this.children.push(view);
},
getRenderData: function(){
return {
children: this.children
}
},
render: function(){
var data = this.getRenderDate();
// render self
this.$el.html(this.template(data));
// then render children
this.renderChildren();
},
renderChildren: function(){
_.each( this.children, function(child){
this.assign(child, '#' + child.cid);
}, this);
},
assign: function (view, selector) {
view.setElement(this.$(selector)).render();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment