Skip to content

Instantly share code, notes, and snippets.

@kn0ll
Last active December 19, 2015 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kn0ll/5868480 to your computer and use it in GitHub Desktop.
Save kn0ll/5868480 to your computer and use it in GitHub Desktop.
simple backbone layout manager (simple subview definitions, with listener cleanup)
Backbone.Layout = Backbone.View.extend({
initialize: function() {
this.viewReferences = {};
Backbone.View.prototype.initialize.apply(this, arguments);
},
setView: function(selector, view) {
var $foundViewNode = $(selector, this.$el),
previousView = this.viewReferences[selector];
if (previousView) {
previousView.stopListening();
}
this.viewReferences[selector] = view;
view.setElement($foundViewNode);
},
remove: function() {
var views = this.viewReferences;
for (var i = 0; i < views.length; i++) {
views[i].stopListening();
// todo: this is only a shallow cleanup. need recursive / deep cleanup
}
return Backbone.View.prototype.remove.apply(this, arguments);
},
// returns the data to be passed to the template function
getTemplateData: function() {
var model = this.model? this.model.toJSON():
(this.collection? this.collection.toJSON(): {});
return model;
},
// a function that accepts view data
// and returns html to populate the view
template: function(templateData) {
return '';
},
// renders the layout and its subviews
render: function() {
var self = this,
views = self.views || [],
$el = this.$el,
$content = self.template(self.getTemplateData());
// render current
$el.empty();
$el.append($content);
// render subviews
_.each(_.keys(views), function(selector) {
var view = views[selector].apply(self);
self.setView(selector, view);
view.render();
});
return this;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment