Backbone JS Collectoin-Model tests
by mickeyvip
HTML
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<div class='container'></div>
JavaScript
$(function() {
var M = Backbone.Model.extend({});
var C = Backbone.Collection.extend({
model: M
});
var V = Backbone.View.extend({
tagName: 'li',
templateHtml: '<button class="cmd-do">x</button><span><%= name %></span>',
initialize: function() {
this.template = _.template(this.templateHtml);
},
render: function() {
this.$el.attr("id", this.model.id);
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var CV = Backbone.View.extend({
tagName: 'div',
className: 'box',
templateHtml: '<ul class="list"></ul><div id="con"><p>Total models: <%= totalModels %></div>',
events: {
'click .cmd-do': 'doRemove'
},
initialize: function() {
this.template = _.template(this.templateHtml);
this.render();
this.model.on('remove add', this.render, this);
},
render: function() {
this.$el.empty();
this.$el.append(this.template({
totalModels: this.model.length
}));
this.model.each(function(model) {
var v = new V({
model: model
});
this.$el.find('.list').append(v.render().el);
}, this);
return this;
},
doRemove: function(e) {
var li = $(e.target).parent('li');
var id = li.attr('id');
var model = this.model.get(id);
if (model) { this.model.remove(model); }
}
});
var c1 = new C([
new M({
id: 1,
name: 'item 1'
}),
new M({
id: 2,
name: 'item 2'
})
]);
var c2 = new C([
new M({
id: 3,
name: 'item 3'
}),
new M({
id: 4,
name: 'item 4'
})
]);
var cv1 = new CV({
model: c1
...