Initjs: Provides a great javascript structure for your application

Generally our application has several scripts that are separated by pages, which in turn should be executed only when needed.

The big question is how to do this in a beautiful way and functional. My motivation was to develop a solution for it.

The solution was to create a Gem to use in a Rails application. As Rails work with MVC, it was easy to set up a structure to separate javascripts for each page.

For example, let's make a script to run only on the page that displays a blog entry. Generally our structure would be a controller of Posts and a show action.

Let's assume we have an object called App in javascript, and within it we have another object called Posts, which is the name of our controller. For the action, we create a function inside the object Posts at the end will be something like this:

App.Posts.Show = function() {  
};

Installation

Add this line to your application's Gemfile:

gem 'initjs'  

And then execute:

$ bundle

Run the generator:

rails generate initjs  

Add //= require init.js to your Javascript manifest file (usually found at app/assets/javascripts/application.js).

Usage

Include the Initjs tag in your application layout (usually found at app/view/layouts/application.html.erb) after the body tag.

<%= initjs_tag %>  

The app.js

If you have a commom javascript that you need execute every page, you can put in app/assets/javascripts/app.js.coffee.

App = window.App =  
  Common:
    initPage: ->
      # If you are using the Turbolinks and you need run a code only one time, put something here.
      # if you're not using the turbolinks, there's no difference between init and initPage.
    init: ->
      # Something here. This is called in every page, with or without Turbolinks.
    finish: ->
      # Something here. This is called in every page, with or without Turbolinks.

So, now with Rails 4.0 coming, it was introduced the Trubolinks. The Gem already works with it.

Javascript structure example

The structure you need follow is the same of your controller and action, as I said before. You can use a namespace too.

With Backbone.js

App.Posts.New = Backbone.View.extend({  
  initialize: function() {
    // Javascript for the page "posts/new"
  }
});

App.Posts.Show = Backbone.View.extend({  
  initialize: function() {
    // Javascript for the page "posts/1"
  }
});

// with namespace
App.Blog.Posts.Show = Backbone.View.extend({  
  initialize: function() {
    // Javascript for the page "blog/posts/1"
  }
});

Without Backbone.js

App.Posts.New = function() {  
  // Javascript for the page "posts/new"
};

App.Posts.Show = function() {  
  // Javascript for the page "posts/1"
};

// with namespace
App.Blog.Posts.Show = function() {  
  // Javascript for the page "blog/posts/1"
};

The project is on my Github.