Skip to content

Instantly share code, notes, and snippets.

@azuby
Created February 9, 2012 06:29
Show Gist options
  • Save azuby/1777845 to your computer and use it in GitHub Desktop.
Save azuby/1777845 to your computer and use it in GitHub Desktop.
# file name: app/assets/javascripts/collections/entries.rb
class Raffler.Collections.Entries extends Backbone.Collection
url: '/api/entries'
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
# file name: 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
# file name: 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}"
# file name: app/assets/javascripts/models/entry.rb
class Raffler.Models.Entry extends Backbone.Model
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'})
# file name: app/assets/templates/index.jst.eco
<h1>Raffler</h1>
<ul>
<% for entry in @entries.models: %>
<li><%= entry.get('name') %></li>
<% end %>
</ul>
# file name: app/assets/javascripts/raffler.js.coffee
window.Raffler =
Models: {}
Collections: {}
Views: {}
Routers: {}
init: ->
new Raffler.Routers.Entries()
Backbone.history.start()
$(document).ready ->
Raffler.init()
# file name: config/routes.rb
scope "api" do
resources :entries
end
root to: "main#index"
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
# Gemfile
gem 'backbone-on-rails'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment