Skip to content

Instantly share code, notes, and snippets.

@sarink sarink/backbone.subiews.js

Last active Aug 29, 2015
What would you like to do?
// I wrote this when Backbone was like v0.2 - now there are many many tools like Marionette,
// and even things native to Backbone (like `stopListening`) that invalidate a lot of this
var SubView = Backbone.View.extend({
// tagName: must be implemented
// className: must be implemented
// template: must be implemented
initialize: function() {
this.model.on("change", this.render, this);
this.model.on("close", this.close, this);
render: function(options) {
console.log("rendering subview for",this.model.get("name"));
var defaultOptions = {};
options = typeof options === "object" ? $.extend(true, defaultOptions, options) : defaultOptions;
this.$el.html(this.template({model: this.model.toJSON(), options: options})).fadeIn("fast");
return this;
close: function() {
console.log("closing subview for",this.model.get("name"));"change", this.render, this);"close", this.close, this);
var ViewCollection = Backbone.View.extend({
// el: must be implemented
// subViewClass: must be implemented
initialize: function() {
var self = this;
self.collection.on("add", self.addSubView, self);
self.collection.on("remove", self.removeSubView, self);
self.collection.on("reset", self.reset, self);
self.collection.on("closeAll", self.closeAll, self);
self.collection.reset = function(models, options) {
self.closeAll();, models, options);
reset: function() {
render: function() {
console.log("rendering viewcollection for",this.collection.models);
var self = this;
self.collection.each(function(model) {
return self;
addSubView: function(model) {
var sv = new this.subViewClass({model: model});
removeSubView: function(model) {
closeAll: function() {
this.collection.each(function(model) {
// usage
var PartView = SubView.extend({
tagName: "tr",
className: "part",
template: _.template($("#part-row-template").html())
var PartListView = ViewCollection.extend({
el: $("table#parts"),
subViewClass: PartView
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.