Coffee script events handling

Hi all,

Currently I’m working on a ruby on rails project and I have to say, I’m
loving all the neat conventions.

Now I would like to integrate some Javascript into my project, with the
use
of Coffee script.

But I have to admit, I have little knowledge about Javascript, and even
less about Coffee script.

Having said that, I would still like to try to use it.

Anyway, what I want is this: I want a button on my webpage that, when
clicked, gives me an alert box.

What I would write in HTML:

Test

And in the included JS file:

window.onload = function() {

$(“test_button”).onclick = test_func;

}

function test_func(){

alert(‘it works!’);

}

I tested this, and it does exactly what I want.

Now, the corresponding HAML code I’m using is:

.test

%button{:id => ‘test_button’} Test

And in Coffee script:

test_func = -> alert ‘it works!’

window.onload = -> $(‘test_button’).onclick = test_func

This does create a button with the text ‘Test’ on there.

But when I try the code above, it does not preform any action…

I have the feeling it’s because I’m unaware of some rails convention.

Can maybe somebody help me with my problem?

Versions I’m using:

  • Ruby: 1.9.3p5
  • Rails: 3.1.3
  • Haml: 3.1.4
  • Coffee-script: (2.2.0)

I hope this was enough information.

Please let me know if anything is unclear

Kind regards,

Ron

It actually has to do with your jQuery code. $() actually returns a
jQuery instance with all the jQuery methods. onclick is not an actual
jQuery method; you need to use the alternative
click and pass it the function. Like
so:

window.onload = function() {
    $('#test_button').click(test_func);
}

function test_func() {
    alert('it works!');
}

P.S. $() is a CSS-selector. Ergo, passing it test_button means that
you want the test_button tag. You should prefix it with the
id-selector (#).

Jeej, this finally works ^^.
The CS code I’ve written is:

test_func = -> alert ‘it works!’
window.onload = -> $(’#test_button’).click test_func

Thanks a lot for your help

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs