你如何限制CoffeeScript(或JavaScript)执行到Rails 3.1中的特定控制器和操作? [英] How do you limit CoffeeScript (or JavaScript) execution to a particular controller and action in Rails 3.1?

查看:100
本文介绍了你如何限制CoffeeScript(或JavaScript)执行到Rails 3.1中的特定控制器和操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的Rails 3.1资源管道非常不错,但由于所有CoffeeScript(或JavaScript)文件被整合到每个页面中包含的单个文件中,因此会出现以下问题:



如何将我的脚本的执行限制到特定的控制器或操作?在我的CoffeeScript中有一种方法知道在请求期间使用了哪个控制器和操作,以便我可以把条件语句放在我的脚本中?



或者我接近这个

> Trevor Burnham 在这里很好地回答了这个问题: rails 3.1 rc1 javascript and asset pipeline



他说:


有两种常见的方法:


  1. 使行为以特定元素的存在为条件。对于
    实例,运行注册表
    的代码应该以



    ').length> 0


  2. 使行为以 body 元素上的类为条件。你可以
    使用ERB设置body类。这是
    经常需要的样式表为
    好​​。代码将是



    if $('body')。hasClass'user'



如果您对CoffeeScript感兴趣,Trevor正在编写一本书,非常好: http://pragprog.com/titles/tbcoffee/coffeescript


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: rails 3.1 rc1 javascript and asset pipeline

He says:

There are two common approaches:

  1. 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

  2. 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

这篇关于你如何限制CoffeeScript(或JavaScript)执行到Rails 3.1中的特定控制器和操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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