04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 18: Advanced Techniques<br />

In this example, a curried version of add() is created that has the first argument bound to 5. When<br />

curriedAdd() is called and 3 is passed in, the 3 becomes the second argument of add() , while the first<br />

is still 5, resulting in the sum of 8. You can also provide all function arguments as shown in this example:<br />

function add(num1, num2){<br />

return num1 + num2;<br />

}<br />

var curriedAdd = curry(add, 5, 12);<br />

alert(curriedAdd()); //17<br />

Here, the curried add() function provides both arguments, so there ’ s no need to pass them in later.<br />

Function currying is often included as part of function binding, creating a more complex bind()<br />

function. For example:<br />

function bind(fn, context){<br />

var args = Array.prototype.slice.call(arguments, 2);<br />

return function(){<br />

var innerArgs = Array.prototype.slice.call(arguments);<br />

var finalArgs = args.concat(innerArgs);<br />

return fn.apply(context, finalArgs);<br />

};<br />

}<br />

The major changes from the curry() function are the number of arguments passed in to the function<br />

and how that affects the result of the code. Whereas curry() simply accepts a function to wrap, bind()<br />

accepts the function and a context object. That means the arguments for the bound function start at the<br />

third argument instead of the second, which changes the first call to slice() . The only other change is<br />

to pass in the context object to apply() on the third - to - last line. When bind() is used, it returns a<br />

function that is bound to the given context and may have some number of its arguments set already. This<br />

can be useful when you want to pass arguments in to an event handler in addition to the event object,<br />

such as this.<br />

var handler = {<br />

message: “Event handled”,<br />

};<br />

handleClick: function(name, event){<br />

alert(this.message + “:” + name + “:” + event.type);<br />

}<br />

var btn = document.getElementById(“my-btn”);<br />

EventUtil.addHandler(btn, “click”, bind(handler.handleClick, handler, “my-btn”));<br />

In this updated example, the handler.handleClick() method accepts two arguments: the name of the<br />

element that you ’ re working with and the event object. The name is passed in to the bind() function as<br />

the third argument and then gets passed through to handler.handleClick() , which also receives the<br />

event object.<br />

597

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!