#323 Backbone on Rails Part 1 pro
In this first part of a two part series you will learn basic Backbone concepts including models, collections, routers, views and events. The backbone-on-rails gem is used for Rails integration with the asset pipeline.
- Download:
- source codeProject Files in Zip (49.7 KB)
- mp4Full Size H.264 Video (37.3 MB)
- m4vSmaller H.264 Video (19.2 MB)
- webmFull Size VP8 Video (23.9 MB)
- ogvFull Size Theora Video (37.9 MB)
Resources
terminal
rails new raffler rails g controller main index --skip-javascripts rails g backbone:install rails g backbone:scaffold entry rails g resource entry name winner:boolean --skip-javascripts rake db:migrate rake db:seed
in_browser.js
entries = new Raffler.Collections.Entries() entries.length entries.fetch() entry = entries.shuffle()[0] entry.get('name') entry.set({'winner': true}) entry.save() entries.create({'name': 'Avdi Grimm'})
Gemfile
gem 'backbone-on-rails'
config/routes.rb
scope "api" do resources :entries end root to: "main#index"
entries_controller.rb
class EntriesController < ApplicationController respond_to :json def index respond_with Entry.all end def show respond_with Entry.find(params[:id]) end def create respond_with Entry.create(params[:entry]) end def update respond_with Entry.update(params[:id], params[:entry]) end def destroy respond_with Entry.destroy(params[:id]) end end
app/assets/javascripts/raffler.js.coffee
window.Raffler = Models: {} Collections: {} Views: {} Routers: {} init: -> new Raffler.Routers.Entries() Backbone.history.start() $(document).ready -> Raffler.init()
app/assets/javascripts/routers/entries_router.js.coffee
class Raffler.Routers.Entries extends Backbone.Router routes: '': 'index' 'entries/:id': 'show' initialize: -> @collection = new Raffler.Collections.Entries() @collection.fetch() index: -> view = new Raffler.Views.EntriesIndex(collection: @collection) $('#container').html(view.render().el) show: (id) -> alert "Entry #{id}"
app/assets/javascripts/models/entry.js.coffee
class Raffler.Models.Entry extends Backbone.Model
app/assets/javascripts/collections/entries.js.coffee
class Raffler.Collections.Entries extends Backbone.Collection url: '/api/entries'
app/assets/javascripts/views/entries/entries_index.js.coffee
class Raffler.Views.EntriesIndex extends Backbone.View template: JST['entries/index'] initialize: -> @collection.on('reset', @render, this) render: -> $(@el).html(@template(entries: @collection)) this
app/assets/templates/index.jst.eco
<h1>Raffler</h1> <ul> <% for entry in @entries.models: %> <li><%= entry.get('name') %></li> <% end %> </ul>