Last active
December 17, 2015 09:09
-
-
Save laser/5585470 to your computer and use it in GitHub Desktop.
A collection of views, in Backbone
This file contains hidden or 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
window.BaseListView = window.BaseView.extend({ | |
close: function() { | |
this._closeAllSubViews(); | |
window.BaseView.prototype.close.call(this); | |
}, | |
initialize: function(options) { | |
this._subViews = []; | |
this.collection.on("add", this._renderSubView, this); | |
this.collection.on("reset", this._renderSubViews, this); | |
this.collection.on("remove", this._closeSubView, this); | |
_.bindAll(this); | |
}, | |
render: function() { | |
this._renderSubViews(); | |
return this; | |
}, | |
_checkEmpty: function() { | |
if (this._subViews.length === 0) { | |
this._emptyView = new this.getEmptyViewPrototype()(); | |
this.$el.append(this._emptyView.render().$el); | |
} | |
else if (this._emptyView) { | |
this._emptyView.close(); | |
} | |
}, | |
_closeSubView: function(model) { | |
var index, i, len; | |
for (i = 0, len = this._subViews.length; i < len; i++) { | |
if (this._subViews[i].model.cid === model.cid) { | |
index = i; | |
break; | |
} | |
} | |
this._subViews[index].close(); | |
this._subViews.splice(index, 1); | |
this._checkEmpty(); | |
}, | |
_renderSubView: function(model) { | |
this._subViews.push(new this.getSubViewPrototype()({ | |
model: model | |
})); | |
this.$el.append(this._subViews[this._subViews.length - 1].render().$el); | |
}, | |
_closeAllSubViews: function() { | |
_.each(this._subViews, function(row) { | |
row.close(); | |
}); | |
this._subViews = []; | |
}, | |
_renderSubViews: function() { | |
this._closeAllSubViews(); | |
_.each(this.collection.models, this._renderSubView); | |
} | |
}); | |
window.BaseItemView = Backbone.View.extend({ | |
close: function() { | |
this.stopListening(); | |
this.remove(); | |
}, | |
render: function() { | |
var merged = _.template(this.template, this.model.toJSON()); | |
this.$el.html(merged); | |
return this; | |
} | |
}); | |
window.SingleContactView = window.BaseView.extend({ | |
template: (function() { | |
return '\ | |
<div><%= first_name %></div>\ | |
<div><%= email_address %></div>'; | |
})() | |
}); | |
window.ContactListView = window.BaseListView.extend({ | |
getEmptyViewPrototype: function() { | |
return window.NoContactsView; | |
}, | |
getSubViewPrototype: function() { | |
return window.SingleContactView; | |
} | |
}); | |
window.NoContactsView = window.BaseView.extend({ | |
"render": function() { | |
this.$el.html(this.template); | |
}, | |
template: (function() { | |
return "Sorry, you ain't got no friends."; | |
})() | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment