You are on page 1of 15

backbone.

js + rails getting started guide


by Yury Omelchuk (c) 2012

____ _ _ _ | _ \ | | | | (_) | |_) | __ _ ___| | __| |__ ___ _ __ ___ _ ___ | _ < / _` |/ __| |/ /| '_ \ / _ \| '_ \ / _ \ | / __| | |_) | (_| | (__| < | |_) | (_) | | | | __/_| \__ \ |____/ \__,_|\___|_|\_\|_.__/ \___/|_| |_|\___(_) |___/ _/ | |__/ (_'___________________________________________________'_) (_.._)

Jeremy Ashkenas, DocumentCloud Inc. http://documentcloud.github.com/backbone 41kb 13.8kb, packed 4.6kb gzipped

alternatives

SproutCore 2 / Ember.js Knockout.js Batman.js Spine.js

components

Router Model Collection View History Events Sync Utility

rails integration

app/ assets/ javascripts/ collections/ movies.js models/ movie.js routers/ movies_router.js views/ todos/ todos_index.js templates/ movies/ index.jst.ejs show.jst.ejs movie.jst,ejs

application.js
//= require jquery //= require jquery_ujs //= require twitter/bootstrap //= require underscore //= require backbone //= require app //= require_tree ./models //= require_tree ./collections //= require_tree ./views //= require_tree ./routers //= require_tree ../templates //= require_tree .

layout
views/layouts/application.html.erb

<%= yield :javascript %> <div id=app></div>


views/main/index.html.erb

<%= content_for :javascript do -%> <%= javascript_tag do %> App.init(); <% end %> <% end -%>

app.js
var App = { Models: {}, Collections: {}, Views: {}, Routers: {}, init: function() { new App.Routers.Movies(); Backbone.history.start(); } };

router

App.Routers.Movies = Backbone.Router.extend({ routes: { "": "index", }, index: function() { var movies = new Movies; movies.fetch({ success: function() { new App.Views.Index( {collection: movies} ) } }) } }

collection
Movies = Backbone.Collection.extend({ model: Movie, url: '/movies' });

view
App.Views.Index = Backbone.View.extend({ initialize: function() { _.bindAll(this, 'render'); this.collection.bind('change', this.render); this.render(); }, render: function() { $(this.el).html(JST['movies/index']( {collection: this.collection })); $('#app').html(this.el); } });

template
<% if (collection.models.length > 0) { %> <% collection.each(function(item, key, list) { %> <div class="row"> <div class="span16 movie"> <h3> <a href="#movie/<%= item.id %>"><%= item.escape('title') %></a> </h3> <%= item.get('description') %> </div> </div> <% }); %> <% } else { %> <p>no movies</p> <% } %>

test!
describe "Backbone", :js do context "no data" do specify "homepage" do visit '/' page.should have_content 'no movies' end end context "with existing data" do before { @movie = Factory :movie, title: 'Pulpfiction' } specify "homepage with data" do visit '/' page.should have_content 'Pulpfiction' end end end

carry on
http://github.com/jurgens/backbone-demo

You might also like