Created
March 7, 2016 16:17
-
-
Save tbcorr/7bbd776cf058d2b8f122 to your computer and use it in GitHub Desktop.
A base Backbone.js View for Composite Views
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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