backbone model collection test
See if we can retrieve collection(s) from our models.
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<body></body>
JavaScript
(function() {
window.App = {
Models: {},
Views: {},
Collections: {}
};
App.Models.Person = Backbone.Model.extend({
defaults: {
name: 'John',
phone: '555-555-5555'
}
});
App.Views.Person = Backbone.View.extend({
tagName: 'li',
template: _.template("<%= name %> -- <%= phone %>"),
render: function(){
var template = this.template( this.model.toJSON() );
console.log(this.model);
this.$el.html( template );
return this;
}
});
App.Collections.People = Backbone.Collection.extend({
model: App.Models.Person
});
App.Views.People = Backbone.View.extend({
tagName: 'ul',
add: function(person){
var personView = new App.Views.Person({a:1,b:2});
this.$el.append( personView.render().el );
return this;
},
render: function() {
this.collection.each(this.add, this);
return this;
}
});
})();
var mary = new App.Models.Person({name: 'Mary'});
var david = new App.Models.Person({name: 'David'});
var tiffany = new App.Models.Person({name: 'Tiffany'});
var people = new App.Collections.People([mary, david, tiffany]);
var girls = new App.Collections.People([mary, tiffany]);
console.log('people',people);
console.log('girls',girls);
console.log('mary', mary);
console.log('david', david);