0

carts.js.coffee

$(document).ready ->
    add_book: () ->
        alert "hihi!!"

I have tried to invoke window.add_book(); and add_book(); in

add_to_cart.js.erb

But both can not work.

add_book();
window.add_book();

And there didn't display the error on Firebug or Webrick console

By the way, I can not understand

What is the meaning when vars or functions in

(function() {})

or when function embraced by {{ }}

({
add_book: function() {
return alert("poc123!!");
}
});

Is there any tutorial or keyword term can let me find related resources?

Thanks in advance

newBike
  • 14,385
  • 29
  • 109
  • 192

2 Answers2

2

The reason is you can't use $(document).ready in js erb or coffee erb.

When you deliver this js erb through Ajax, document has been ready for a long time. The functions inside your erb will never get chance to be called if they are under document ready.

So the simple fix is, remove document ready, and invoke the functions directly.

Billy Chan
  • 24,625
  • 4
  • 52
  • 68
0

I'm not sure what you expect using add_book: inside a function, but that's certainly not what you wanted. Here is the generated javascript for your code :

$(document).ready(function() {
  return {
    add_book: function() {
      return alert("hihi!!");
    }
  };
});

You are returning an object containing the function, but no one can access it since it's not referenced by anyone.

What you want is a variable, able to contain a reference :

$(document).ready ->
    window.add_book = () ->
        alert "hihi!!"

Now, you can use it anywhere (after domready, of course), calling directly add_book().

If your use chrome, this extension may help you to spot coffeescript problems : it's a live shell that let you see the computed js and run coffeescript code.

On a side note, I would recommend against using coffeescript until you feel fluent with javascript.

kik
  • 7,867
  • 2
  • 31
  • 32