How do you limit CoffeeScript (or JavaScript) execution to a particular controller and action in Rails 3.1?

前端 未结 5 684
攒了一身酷
攒了一身酷 2021-01-02 09:50

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 raise

5条回答
  •  独厮守ぢ
    2021-01-02 10:36

    Trevor Burnham answers this question nicely here: How do I associate a CoffeeScript file with a view?

    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

提交回复
热议问题