Created
November 16, 2012 01:02
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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