Skip to content

Instantly share code, notes, and snippets.

@zachmayberry
Created November 16, 2012 01:02
Show Gist options
  • Save zachmayberry/4082957 to your computer and use it in GitHub Desktop.
Save zachmayberry/4082957 to your computer and use it in GitHub Desktop.
A simple reference example for rendering a collection in a list view using Backbone.js
(function() {
// Model
var User = Backbone.Model.extend({
defaults: {
name: '',
email: '',
password: ''
},
url: '/users',
idAttribute: '_id'
});
// Collection
var Users = Backbone.Collection.extend({
model: User,
url: '/users'
});
// Template
var list = "<% _.each(collection, function(user) { %><li><%= user.name %></li><% }); %>";
// View
var UserList = Backbone.View.extend({
el: '#users',
initialize: function() {
this.template = _.template( list );
this.collection.bind("reset", this.render, this);
},
render: function() {
$(this.el).html( this.template({ collection: this.collection.toJSON() }) );
return this;
}
});
// Usage
var users = new Users;
users.fetch({
success: function(users) {
console.log(JSON.stringify(users.models));
},
error: function(err) {
console.log(err);
}
});
var userList = new UserList({ collection: users });
users.reset();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment