Skip to content

Instantly share code, notes, and snippets.

@chadwilcomb
Last active August 29, 2015 14:15
Show Gist options
  • Save chadwilcomb/18037a4ce0be22ec67fa to your computer and use it in GitHub Desktop.
Save chadwilcomb/18037a4ce0be22ec67fa to your computer and use it in GitHub Desktop.
Backbone Nested Views
//[Taken from Sam Breed's talk at BackboneConf III] (http://youtu.be/QqSHrpro02g?t=21m15s)
//Parent View
App.Views.ParentView = Backbone.View.extend({
renderChildView: function (model) {
var view = this.children[model.cid];
if (view === undefined) {
view = this.children[model.cid] = new App.Views.ChildView({ model: model });
}
return view.render().$el;
},
render: function () {
this.$el.html( this.collection.map(this.renderChildView, this) );
},
removeMe: function () {
//Removes all child views from the DOM, calls stopListening to remove any bound events that the view has listenTo'd.
_.each(this.children, function (child) {
child.remove();
});
this.remove();
}
});
//Child View
App.Views.ChildView = Backbone.View.extend({
template: _.template($('#childViewTemplate').html()),
render: function () {
this.$el.html(this.template(this.model.attributes));
return this;
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment