Nov

28

If you are a user of JavaScript Framework Prototype, and use observe to handle event, you may face problem when you try to call function with variable inside the observe.

Let’s assume you have an HTML element with the id btn, you want to alert a custom message when it’s clicked, you might code it the following way:

function alertMessage(message) {
    alert(message);
}
$('btn').observe('click', alertMessage('hullo world'));

this won’t work because it involves <strong>currying</strong>. Currying? What the heck is that? You may ask, ok, let me try to explain this:

Because <strong>alertMessage</strong> is a function and <strong>message</strong> is an argument, to write it in the observe event handler, we must produce a new function by combining function <strong>alertMessage</strong> and its argument <strong>message</strong>, this is called <strong>currying</strong>.


The bad news is that JavaScript doesn’t have a build-in curry method, but the good news is that Prototype has one! So to make the above script work, all you need to do is to add in the curry!

function alertMessage(message) {
    alert(message);
}
$('btn').observe('click', alertMessage.curry('hullo world'));

For more about currying, check out the following two great Google book excerpts, one by Yahoo! Architect Douglas Crockford and another by Core Prototype developer Andrew Dupont.

http://books.google.com/books?id=PXa2bby0oQ0C&pg=PA43&lpg=PA43
http://books.google.com/books?id=GtLXnZWH3-4C&pg=PP10

Hope this helps!



Similar Posts

Comments

Name (required)

Email (required)

Website

Speak your mind

Sponsors




Links