Sunday, December 30, 2012

Using requirejs with backbonejs (Rails)

So, after fighting with it for hours, finally I got it working so I thought it might help someone. I will got through step by step

1 - Create a new Rails application and set it up so that it loads an empty index page
     (Create a controller with an index action + add an index view + edit the routes file accordingly)

2 - Add the following line to the Gemfile - gem 'requirejs-rails'


3 - In application.html.erb file, replace
     <%= javascript_include_tag "application" %> with <%= requirejs_include_tag "application" %>


4 - Add a requirejs.yml file under config directory and delete all the content of application.js

5 - In the vendor/assets/javascripts directory, add backbone.js, underscore.js and JQuery libraries

6 - Add the code as shown below to the corresponding files
   
    
-----------------------------------------------
application.js
-----------------------------------------------
require [
'backbone',
'path/to/router/with/index/handler'],
(Backbone, IndexRouter) ->
$ ->
Main = new IndexRouter()
Backbone.history.start()
-----------------------------------------------
requirejs.yml
-----------------------------------------------
modules:
- name: 'application'
shim: {
'backbone': {
# These script dependencies should be loaded before loading
# backbone.js
deps: ['underscore', 'jquery'],
# Once loaded, use the global 'Backbone' as the
# module value.
exports: 'Backbone'
}
}
------------------------------------------------
MainRouter.js
------------------------------------------------
define [
'backbone'],
(Backbone, $) ->
class IndexRouter extends Backbone.Router
routes:
'': 'index'
index: () ->
alert("wooo..It works")


7 - Credit goes to - https://github.com/jwhitley/requirejs-rails

8 - Thanks

2 comments: