Backbone.js binding models and collections
Bind models and collection to catch the remove event and change event.
by Atinux
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script src="https://raw.github.com/derickbailey/backbone.modelbinding/master/backbone.modelbinding.min.js"></script>
<script src="https://raw.github.com/derickbailey/backbone.memento/master/backbone.memento.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
JavaScript
var Model = Backbone.Model.extend({
initialize: function () {
// BINDS
this.bind('change', this.update);
},
update: function () {
console.log('Model changed !');
},
remove: function () {
console.log('Model removed !');
}
});
var Collection = Backbone.Collection.extend({
initialize: function () {
this.bind('remove', this.removeModel);
},
removeModel: function (models) {
if (models.length) {
_.each(models, function (model) {
console.log(model);
model.remove();
});
}
else {
models.remove('remove');
}
}
});
var model = new Model();
var collection = new Collection();
collection.add(model);
model.set({ coucou: 'oui' });
collection.remove(model);