Skip to content

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

Notifications You must be signed in to change notification settings

falm/js-namespace-rails

Repository files navigation

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

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •