如何使用Rails资产管道执行每页javascript [英] How to do per-page javascript with the Rails asset pipeline

查看:44
本文介绍了如何使用Rails资产管道执行每页javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解出于性能原因,最好让资产管道连接并缩小我的所有JavaScript,并在每个页面请求中全部发送.很公平

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

但是,我的一堆JavaScript就像是将特定行为绑定到特定页面元素之类的东西-

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); }

,如果我知道此代码仅在该页面上执行,而不是在其他页面上执行,而这些页面可能恰巧具有相同的ID或与相同的选择器匹配,那么我会感到更加自在.人们如何处理呢?

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?

我不想将所有这些内容都内联到元素中,只是因为当它的长度超过大约两行时,将javascript正确缩进.html.erb文件中会比需要做的工作还要多

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

推荐答案

这就是我要做的事情(基于一些stackoverflow的答案):

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

application_helper.rb

application_helper.rb

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

application.html.haml

application.html.haml

  %body{data: {page: body_page_name}}

application.js

application.js

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

在适当的js文件中,有一个名为ControllerAction的对象:

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

tickets.js

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

这篇关于如何使用Rails资产管道执行每页javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆