0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

that was exactly the help I needed. Thanks for taking the time to put together this response. Everything's working now that I specified the load order in application.js and defined my global functions with window. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.