Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do per-page javascript with the Rails asset pipeline

I understand that for performance reasons it is better to let the asset pipeline concatenate and minify all my javascript and send the whole lot with every page request. That's fair enough

However, a bunch of my javascript is things like binding specific behaviours to specific page elements - stuff like

$('button').click(function(e) { $('input.sel').val(this.name); }

and I would feel more comfortable if I knew that this code was being executed only on that page - not on evey other page which might coincidentally have elements with the same IDs or which matched the same selectors How do people deal with this?

I would rather not put all this stuff inline in elements, just because when it gets to be more than about two lines long, keeping javascript correctly indented inside an .html.erb file is more work than it needs to be

like image 897
telent Avatar asked Jan 23 '12 18:01

telent


1 Answers

Here is what I do (based on some stackoverflow answers):

application_helper.rb

def body_page_name
  [controller_name.classify.pluralize, action_name.classify].join
end

application.html.haml

  %body{data: {page: body_page_name}}

application.js

$(function() {
  var page = $("body").data("page");
  if("object" === typeof window[page])
    window[page].init();
});

And in appropriate js file there's an object called ControllerAction:

tickets.js

var TicketsShow = new function() {
  var self = this;

  self.init = function() {
    // code which may call other functions in self
  };
};

There's probably better way to do it, but this works for me

like image 141
Ineu Avatar answered Oct 08 '22 03:10

Ineu