falm / js-namespace-rails

js-namespace-rails let you choose which javascript snippet can execute in rails assets pipeline

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

JsNamespaceRails Build Status Coverage Status Code Climate Dependency Status Gem Version

Rails's asset pipeline compiles all of js file into a single file which is executed on all pages. There has a problem, some time we want to execute selective code on specific page, but asset pipeline doesn't support. js-namespace-rails can handle this problem by using it's method to namespace and selectively execute certain javascript depending on which Rails controller action is active.

Installation

Add this line to your application's Gemfile:

gem 'js-namespace-rails'

Setup

Require js-namespace-rails file in application.js or other main file, notice js-namespace-rails has no dependency

//= require js-namespace-rails

Usage

Assume your project have articles_controller

class ArticlesController < ApplicationController
  def index
  end
end

And its corresponding js file app/assets/javascripts/articles.js.erb

then you just need to write below into the js file

// app/assets/javascripts/articles.js.erb
JsSpace.on('articles', {
  init: function(){
  	console.log('common logic of article in here');
  },
  index: function(){
  	console.log('logic of index action in here');
  }
});

Feature

Passing Parameters to js

class ArticlesController < ApplicationController
  def show
    @article = Article.find(params[:id])
    js author: @article.author
    # also you can passing an object
    js article: @article
  end
end
// app/assets/javascripts/articles.js.erb
JsSpace.on('articles', {
  show: function(){
    console.log(this.params.author); // get author from params
    console.log(this.params.article.title); // get title of article
  }
});

License

MIT License.

About

js-namespace-rails let you choose which javascript snippet can execute in rails assets pipeline


Languages

Language:Ruby 70.1%Language:HTML 17.2%Language:JavaScript 10.3%Language:CSS 2.1%Language:Shell 0.3%