Skip to content

Instantly share code, notes, and snippets.

@pixelhandler
Created February 26, 2012 02:12
Show Gist options
  • Save pixelhandler/1912291 to your computer and use it in GitHub Desktop.
Save pixelhandler/1912291 to your computer and use it in GitHub Desktop.
Product API example using Backbone.js Models, Views and Collections
// bootstrap
PX.app = new PX.App();
Backbone.history.start();
<script type="text/template" id="product-template">
<p><a href="products/{{_id}}">{{title}}</a></p>
<p>{{description}}</p>
<p>ID: {{_id}}</p>
</script>
PX.ProductList = Backbone.Collection.extend({
model: PX.Product,
url: '/api/products',
initialize: function () {
this.fetch({
success: this.fetchSuccess,
error: this.fetchError
});
this.deferred = new $.Deferred();
},
deferred: Function.constructor.prototype,
fetchSuccess: function (collection, response) {
collection.deferred.resolve();
},
fetchError: function (collection, response) {
throw new Error("Products fetch did get collection from API");
}
});
PX.products = new PX.ProductList();
PX.ProductListItemView = Backbone.View.extend({
tagName: "li",
className: "product",
initialize: function (options) {
this.template = $('#product-template').html();
},
render: function () {
var markup = Mustache.to_html(this.template, this.model.toJSON());
this.$el.html(markup).attr('id',this.model.get('_id'));
return this;
}
});
PX.ProductListView = Backbone.View.extend({
tagName: "ul",
className: "products",
render: function () {
for (var i = 0; i < this.collection.length; i++) {
this.renderItem(this.collection.models[i]);
};
$(this.container).find(this.className).remove();
this.$el.appendTo(this.options.container);
return this;
},
renderItem: function (model) {
var item = new PX.ProductListItemView({
"model": model
});
item.render().$el.appendTo(this.$el);
}
});
// model
PX.Product = Backbone.Model.extend({
defaults: {
title: null,
description: null
}
});
PX = window.PX || {};
// application
PX.App = Backbone.Router.extend({
routes: {
"/": "listProducts",
"list": "listProducts"
},
//initialize: function (options) {},
listProducts: function () {
var productsList = new PX.ProductListView({
"container": $('#container'),
"collection": PX.products
});
PX.products.deferred.done(function () {
productsList.render();
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment