12

I am new to the prototype framework and am trying something really simple and failing. I am trying to respond to a click event on a button like so:

$$('.btn').observe('click', respond);
function respond(event) {
    alert("hello");
}

Why isn't this working? Please help!

2 Answers 2

22

Unlike jQuery, handing selectors with multiple results in Prototype works a little differently. You need to handle each selected result separately using .each().

$$('.btn').each(function(element) {
    element.observe('click', respond);
})

This is one of the reasons I moved over to jQuery. The other reason: knowing jQuery is marketable and knowing Prototype is not.

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

6 Comments

Thats just stupid. Thanks. I am from a jquery background and am being forced to use prototype for an upcomming project - from what i have seen it is miles behind jquery with regards to dom manipulation
Also - this is not mentioned in the documentation from what I can see!
I wouldn't say it's miles behind. It can do all of the same things, but not in such a concise manner as jQuery. I worked with it before jQuery came onto the market. Back then it was by far the best choice. But, yeah, doing things with jQuery is sooo much easier.
You can also do the same thing by using "invoke". api.prototypejs.org/language/enumerable/prototype/invoke
Well Prototype was out earlier, so jQuery had a lot to base itself upon.
|
13

Can be also be done with a single-liner, as someone already suggested in a comment:

$$('.btn').invoke('observe', 'click', respond);

Comments

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.