No commit activity in last 3 years
No release in over 3 years
Namespace and Selectively Execute Javascript
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

 Project Readme

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.