Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Backbone.js, Rails, and Handlebars

Backbone.js, Rails, and Handlebars

Taking Backbone.js beyond a todo application; includes interesting rubygems, modeling relationships, advice on getting started, and a little intro to handlebars.

Zachery Moneypenny

March 01, 2012
Tweet

More Decks by Zachery Moneypenny

Other Decks in Programming

Transcript

  1. my_app.js.coffee #= require_self #= require_tree ./routers #= require_tree ./templates #=

    require_tree ./models #= require_tree ./collections #= require_tree ./views window.MyApp = Models: {} Collections: {} Views: {} Routers: {} init: (options) -> @router = new MyApp.Routers.MainRouter(options) Backbone.history.start()
  2. models/person.js.coffee class MyApp.Models.Person extends Backbone.RelationalModel relations: [{ type: Backbone.HasMany, key:

    "phone_numbers", relatedModel: "MyApp.Models.PhoneNumber", collectionType: "MyApp.Collections.PhoneNumbersCollection", reverseRelation: { key: "person" } }] defaults: first_name: null last_name: null url: -> "/people/"+@get("id")+".json"
  3. models/phone_number.js.coffee class MyApp.Models.PhoneNumber extends Backbone.RelationalModel defaults: label: null number: null

    url: -> if @isNew() "/people/"+@get("person_id")+"/phone_numbers.json" else "/people/"+@get("person_id")+"/phone_numbers/"+@get("id")+".json"
  4. Congratulations! Your models are now in a relationship ★ fetchRelated

    to get sub-collections ★ add, remove, and update events exposed ★ traverse from parent to child or vice-versa
  5. <h2>{{first_name}} {{last_name}}</h2> <ul> {{#each phone_numbers}} <li>{{label}}: {{number}}</li> {{/each}} </ul> templates/people/show.jst.hbs

    MyApp.Views.People ||= {} class MyApp.Views.People.ShowView extends Backbone.View template: JST["templates/people/show"] tagName: 'div' views/people/show_view.js.coffee