On Github jandet / columbia-mvc-presentation
Janessa Det / Web Team @TwitterNYC / Follow Me: @jandet
Model: Represents state of data
View: Passive representation of state of model
View Model: Specialized Presenter
Gives structure to web applications by providing:
and connects it all to your existing API over a RESTful JSON interface.
reset (collection)
add (model, collection)
remove (model, collection)
change (model)
change:attribute (model, value)
var Puppy = Backbone.Model.extend({ defaults: { weight: 10 }, eatFood: function() { var currentWeight = this.get("weight"); this.set({weight: currentWeight + 5}); } }); var george = new Puppy({id: 1, name: "George"}); george.eatFood(); george.save();
var PuppyLitter = Backbone.Collection.extend({ urlRoot: 'api/v1/puppies', model: Puppy }); var puppies = new PuppyLitter(); puppies.add(george); puppies.add(spot); puppies.add(bob); /* alternatively */ var initializedPuppies = new PuppyLitter([george, spot, bob]);
collection fetch performs GET on urlRoot endpoint
model fetch performs GET on endpoint urlRoot + model.id
var PuppyRepresentation = Backbone.View.extend({ template: ..., tagName: "div", className: "puppy-style", events: { "click .tail": "wag", "click .bowl.": "feed" }, initialize: function() { this.listenTo(this.model, "change", this.render); // equivalent to this.model.on("change", this.render); }, feed: function() { this.model.eatFood(); }, wag: function() { ... }, render: function() { this.$el.html(this.template(this.model.attributes)); return this; } });Collection view instantiated with collection Collection view fetches, cycles through retrieved models, and instantiates model views for them Collection view calls render on each model view and appends to its associated container/element
var myRouter = Backbone.Router.extend({ routes: { "/": "home", "/djs/:permalink": "djs", "/djs/:permalink/:mixid": "djs" }, home: function() { ... }, djs: function(permalink, mixid) { ... } }); // To start tracking hashchanges Backbone.history.start();