📜 ⬆️ ⬇️

PluggableJs - a simple and convenient way to connect javascript on certain pages

Foreword


If you use Rails> = 3.1 with the included asset pipeline, then of course you know that all the scripts under the require_tree directive (and we’ll talk about them) are compressed into one file and, accordingly, work on all pages. But what to do if a piece of javascript is needed only on one page and is not needed at all on another? Behold! This is the problem that pluggable_js solves.

Why jam


After all, there are other ways (I hope no one writes the code in the view). The most obvious, perhaps, is to write in the required template:
 <% content_for :head do %> <%= javascript_include_tag 'my_fancy_js' %> 

and exclude file from require_tree . But the disadvantage of this approach is that the scripts belonging to a particular controller are not in the same place (which means it is harder to search and understand). In the appendage, if a piece of code is large, then we lose the advantages of the pipeline. The solution used in the jam minimizes the disadvantages described.

How it works


You choose a controller and actions, in which a custom script is needed, and start the generator:
 rails generate pluggable_js Post index new 

It will generate two files in which the Post.index() and Post.new() functions will be called after the DOM loads:
 app/assets/javascripts/pluggable/posts/index.js.coffee app/assets/javascripts/pluggable/posts/new.js.coffee 

Now you just have to describe them in posts.js.coffee:
 window.Post ||= {} Post.index = () -> # your code goes here Post.new = () -> # and here 

A helper <%= javascript_pluggable_tag %> specified in the layout will connect the file if it matches the path and values ​​of the current parameters of the controller / action. Yes, there is an additional request to the server, but this is just a trigger.
')
* I omitted subtleties that are optional to describe ideas, therefore, see the detailed instructions .

Config


Suppose you create an action search, which (like the action index) renders the index template. It turns out that the Post.index() function Post.index() also be called. To do this, you can create config / initializers / pluggable_js.rb and use the setting:
 PluggableJs.config do |config| config.pair_actions = { 'search' => 'index' } end 

{ 'create' => 'new', 'update' => 'edit' } set by default.

Eventually


All scripts related to the controller are in one place. All custom functions fall into the pipeline. And finally, we completely cleared the view from any references to js.

UPD: Thank you all for the comments. Attention , updated the jam, now you do not need to add anything to the config.assets.precompile. Simply declare the functions. It remains to think about the roles. Look at styx jam as an alternative solution.

Thank you verybigman , ExReanimator and owls for the contribution.

Source: https://habr.com/ru/post/194072/


All Articles