如何命名我们的JS用于Rails资产管道 [英] How to namespace our JS for use with the Rails asset pipeline

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

问题描述

我理解rails 3.1资产管道背后的原因:我们在一个整洁,可缓存的文件中编译所有JS以提高性能。太好了,我们想要那个。

I understand the reasoning behind the rails 3.1 asset pipeline: we compile all the JS in a neat, cacheable file to improve performance. Great we want that.

然而,加载所有内容也意味着我们必须非常小心我们不要在多个页面上使用某个ID或类,如果我们有一些JS附加到它。否则,JS将在两个页面上触发,因为它总是被加载。

However, loading everything also means we've got to be very careful that we not use a certain ID or class on multiple pages, if we have some JS attached to it. Or else, the JS will fire on both pages, since its always loaded.

现在,我们想要实现的目标如下:

*我们希望将所有内容保存在一个JS文件中(我们知道如何单独加载文件,只是不要这样)

*我们想要在每个 controller_name中命名JS .js 所以它只在初始化适当的命名空间时加载


*我们想要通过从<$ c上的数据属性读取当前控制器来初始化相应的命名空间$ c>< body> 我们的布局标签

Now, what we want to achieve is the following:
* we want to keep everything in a single JS file (we know how we can load files separately, just don't want that)
* we want to namespace the JS in each controller_name.js so it's only loaded when the appropriate namespace is initialized
* we want to initialize the appropriate namespace by reading the current controller from say a data-attribute on the <body> tag of our layout

问题是:我们不知道如何在JS中实现。特别是,我们应该如何命名JS,然后根据HTML标签的内容动态初始化它。

The problem is: we don't have a good idea how to implement in JS. Particularly, how should we namespace the JS and then dynamically initialize it based on the contents of a HTML tag..

非常感谢任何帮助!

推荐答案

这是一种命名控制器/动作级别所有内容的方法

Here is a way to namespace everything on a controller/action level

  • http://www.viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution/
  • above was inspired by http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/

你基本上是这样声明你的身体

You basically declare you body as such

<body data-controller="<%= controller_name %>" data-action="<%= action_name %>">

然后调用这些方法(每种方法都有一系列方法 - 所以如果你需要的话在每个页面上,它是共同的/ init。或者是所有用户的操作,都在用户/ init上。或者只有用户显示页面?那是用户/显示。

And then these methods are called (which each have a series of methods -- so if you need something on every page, it's in common/init. Or on all users actions, that's on users/init. Or only the users show page? that's users/show.

SITENAME.common.init();
SITENAME.users.init();
SITENAME.users.show();

我已经使用了它并且效果非常好。

I've used this and it works very very well.

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

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