JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
JavaScript
// in application.js
var NS = new function() {
var _modules = [];
// retrieve or initialize a module
this.module = function(key) {
if (!_modules[key]) {
_modules[key] = {};
}
return _modules[key];
}
};
// modules/MyModule.js
(function(module) {
// a model
module.model = Backbone.Model.extend({
// model options
});
// a collection of models
module.collection = Backbone.Model.extend({
model: this.model
});
// the view for a single model
module.modelView = Backbone.View.extend({
render: function() {
// do some rendering
return this;
},
template: _.template('...')
});
// the view for a collection of models
module.collectionView = Backbone.View.extend({
tagName: 'ul',
initialize: function() {
this.views = [];
this.collection.bind('add', this.add);
this.collection.bind('remove', this.remove);
_.bindAll(this);
},
// create a view for the model and redraw the collection
add: function(model) {
var view = new module.modelView({
model: model,
tagName: 'li'
});
this.views.push(view);
this.render();
},
// remove the view for the model and redraw
remove: function(model) {
var view = _.find(this.views, function(view){ return view.model == model; });
this.views = _.without(this.views, view);
this.render();
},
// redraw the entire collection
render: function() {
var self = this;
this.$el.empty();
// render a `modelView` for each model in the collection
_.each(this.views, function(view) {
self.$el.append(view.render().el);
});
return this;
}
});
})(NS.module('MyModule'));
var collection = NS.module('MyModule').collection,
model = NS.module('MyModule').model;
console.log(new collection());
console.log(new model());