Hector Villarreal
Hector Villarreal

Reputation: 822

Uncaught ReferenceError when using the asset pipeline and pjax

Ok, this this sounds like a newbie mistake... but I can't seem to figure out what's going on. I'm relatively new to Rails 3.1, coffeescript and the asset pipeline in general, so I'm having a bit of trouble figuring this one out.

Anyway, here is the problem.

In my Users index.html.erb file I have a button which will load a new user form through ajax. The code to load the form sits in users.js.coffee and the button has an onClick method referring to the function that does that work, like so.

index.html.erb

<%= button_tag "New User", :id => "btn_new_user", :onClick => "loadNewUserForm()", :path => "#{new_user_path}" %>

users.js.coffee

loaded = false

loadNewUserForm = ->
  if not loaded
    @path = $('#btn_new_user').attr("path")
    $("#new-users-container").load(@path)
    loaded = true

for some reason, when I click on the New User button I keep getting

 Uncaught ReferenceError: loadNewUserForm is not defined

I tried binding the function to the click event of the button in the document.ready (declared in users.js.coffee) but the problem with that is that it's not being called because I'm using pjax.

I think I'm not understanding the way asset pipeline works or something...

Thanks in advance for the help.

Upvotes: 1

Views: 1350

Answers (1)

tokland
tokland

Reputation: 67900

When in doubt go to the generated JavaScript to see what's going on. You'll probably see something like this:

(function() {
  // Your code here
}).call(this);

This is the standard mechanism used in Javascript to avoid namespace collision (Coffeescript does it by default), so objects are not visible outside this file unless you explicitly attach them to a global object (window in the browser, exports in node.js, ...).

By the way, note that you are not following the commonly accepted Unobtrusive Javascript guidelines: you should set events using JavaScript, not with inline events in HTML tags. Some references: here and here.

Upvotes: 3

Related Questions