简体   繁体   English

根据Rails中的控制器加载JavaScript文件

[英]Load JavaScript file according to controller in Rails

I have two controllers: 我有两个控制器:

class WelcomeController < ApplicationController
  def index
  end
end
class HomeController < ApplicationController
  def index
  end
end

In my assets folder, I have two JavaScript files: 在资产文件夹中,有两个JavaScript文件:

home.coffee
welcome.coffee

I want to load my script according to the controller: 我想根据控制器加载脚本:

  • home.coffee at home/index path only home.coffeehome/index路径
  • welcome.coffee at welcome/index path only 仅在welcome/index路径中使用welcome.coffee

AFAIK the asset pipeline will concat all the Javascript you specify in the application.js manifest. AFAIK资产管道将合并您在application.js清单中指定的所有Javascript。 For conditional execution, one technique might be to search for a unique ID in the DOM. 对于条件执行,一种技术可能是在DOM中搜索唯一ID。 For example, your home/index view might have a <div id="home" /> element, so in home.coffee , you write: 例如,您的home/index视图可能具有<div id="home" />元素,因此在home.coffee ,您可以编写:

$ -> return unless $('#home').length (...the rest of your code here)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM