简体   繁体   中英

Rails 3.1 Asset Pipeline Javascript - specifying page load though jQuery ->

This is causing me a lot of frustration. I'm hoping someone can help me out.

In my application.js file I have the following:

//= require jquery
//= require jquery_ujs
//= require jquery.remotipart
//= require jquery-ui
//= require jquery.purr
//= require jquery.slides
//= require best_in_place
//= require twitter/bootstrap
//= require_tree .

Do I need to have the following (or its equivalent) in one or all of my page specific Javascripts? I know in production they all get merged into one file with asset pipeline so... Do I lead off one file, no files, all files with this...?

jQuery ->

What I've found is adding "jQuery ->" or "$ ->" to the top of all resource-specific JavaScripts almost works. My problem is I have one resource where nothing works unless I remove the "jQuery ->". Since that resource's JS file interacts with another resource's JS file for functions, etc. I have to remove "jQuery ->" from that as well and that is causing unintended behavior.

Just wondering what the best practice is for js files in asset pipeline and getting them to work together as one.

Thanks

You can't rely on the order of your assets being loaded when using require_tree . So if you are going to use javascript files that are dependent on eachother, make sure to require them in the correct order.

So instead of:

//= require_tree .

Use

//= require posts
//= require comments

And then call functions or whatever you defined in posts in your comments javascript file.

Furthermore, when you are using coffeescript as I assume you do, you have to use a namespace in order for variables to be avaible throughout your application.

So for example.

posts.js.coffee

$ ->
  window.my_super_variable = 'super'

  window.my_super_function = (message) ->
    alert(message)

comments.js.coffee

$ ->
  my_super_variable += ' awesome'

  my_super_function(my_super_variable)

If you don't use window when defining variables or functions they won't be accessible globally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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