Coffee script events handling

23 views
Skip to first unread message

Ron Boortman

unread,
Dec 27, 2011, 2:32:45 PM12/27/11
to rubyonra...@googlegroups.com

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:

<div id="test">

<button id="test_button">Test</button>

</div>


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

Bryan Dunsmore

unread,
Dec 28, 2011, 1:43:12 AM12/28/11
to rubyonra...@googlegroups.com
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`](http://api.jquery.com/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 (#).

--
Posted via http://www.ruby-forum.com/.

Ron Boortman

unread,
Dec 28, 2011, 6:35:44 AM12/28/11
to rubyonra...@googlegroups.com
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
Reply all
Reply to author
Forward
0 new messages