I recently started using Backbone.js with my existing web application and have found it to be extremely useful for keeping all my Javascript front-end code organized. As my application has a complicated user interface, I realized my JavaScript code was getting out of control and was tough to maintain due to lack of structure.
This forced me to look for options with which I could keep my code clean and in a structured way. And I found there are many JS frameworks that attempt to offer similar benefits, like Backbone.js, Ember.js, Angular.js, ExtJs and so on.
However, I decided to go with Backbone because it is one of the most extensively used frameworks in creating application frond-end. It has a very active community and it is also being vastly used in production for a considerable number of big companies like: Trello, Basecamp, DISQUE etc.
In this blog post, I am going to walk you through the steps required to integrate Backbone.js with Rails application.
Steps:
First of all, we need to include Backbone gem in our Rails application. So, open Gemfile and include it.
gem 'rails-backbone'
As we have added new gem to Gemfile, make sure to run bundle update to install all dependencies.
$ bundle update
Backbone gem comes with a fancy scaffold generator which will create the required artifacts for your application.
This creates the following directory structure under app/assets/javascripts/backbone.
backbone/
routers/ (maps HTML routes to actions)
models/ (maintains state)
templates/ (presents clientside views)
views/ (presents model data in the DOM)
In order to setup initial requirements and name spacing, it also creates a coffee script file as app_name.js.coffee.
app/assets/javascript/backbone/app_name.js.coffee
Create a backbone model and collection inside app/assets/javascripts/backbone/models to be used to communicate with rails backend.
$ rails g backbone:model model_name field_name:datatype
We are almost done. Now you need to edit the index view as per requirement.
$(function() {
window.router = new Model.Routers.ModelRouter({controller: });
Backbone.history.start();
});
Now start the server.
$ rails s
Thereafter, browse “localhost:3000/controller” and now you will get a fully functioning backbone app with rails.
For more doubts and questions, do write to us at support@shephertz.com
Leave A Reply