How do you limit CoffeeScript (or JavaScript) execution to a particular controller and action in Rails 3.1?(在 Rails 3.1 中,如何将 CoffeeScript(或 JavaScript)的执行限制为特定的控制器和动作?)
问题描述
The new Rails 3.1 asset pipeline is really nice, but since all CoffeeScript (or JavaScript) files get melded down into a single file that is included in every page, it raises this question:
How do I limit the execution of my script to a particular controller or action? Is there a way within my CoffeeScript to know which controller and action was used during the request so that I can put conditional statements in my script?
Or am I approaching this the wrong way altogether?
Trevor Burnham answers this question nicely here: How do I associate a CoffeeScript file with a view?
He says:
There are two common approaches:
Make behavior conditional on the presence of a particular element. For instance, code to run a signup sheet should be prefaced with something like
if $('#signup').length > 0
Make behavior conditional on a class on the
body
element. You can set the body class using ERB. This is often desirable for stylesheets as well. The code would be something like
if $('body').hasClass 'user'
And if you're interested in CoffeeScript, Trevor is working on a book that looks to be very good: http://pragprog.com/titles/tbcoffee/coffeescript
这篇关于在 Rails 3.1 中,如何将 CoffeeScript(或 JavaScript)的执行限制为特定的控制器和动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Rails 3.1 中,如何将 CoffeeScript(或 JavaScript)的执行限制为特定的控制器和动作?
基础教程推荐
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 动态更新多个选择框 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01