views:

165

answers:

1

I'm trying to understand why people use a wrap function for my event handlers. For example:

Example.prototype.wrap = function(obj, method) {
   return function(event) {
      obj[method](event);
   }
}

Basically, what is wrap used for?

Edit: From the example linked below, the code is:

String.prototype.capitalize = String.prototype.capitalize.wrap( 
  function(proceed, eachWord) { 
    if (eachWord && this.include(" ")) {
      // capitalize each word in the string
      return this.split(" ").invoke("capitalize").join(" ");
    } else {
      // proceed using the original function
      return proceed(); 
    }
  }); 

"hello world".capitalize()     // "Hello world" 
"hello world".capitalize(true) // "Hello World"

I see that the wrap function has a function inside, but I'm confused to the syntax. The wrap function wraps function(proceed, eachWord) { blah }, but what is proceed and what is eachWord in this case? I think eachWord is the paramater passed into capitalize ("hello world".capitalize(true)) but I don't know what proceed is.

Also, how did this code know where to pass the 'true' value, and to which variable is it assigned in the code? (ie, which param is it?)

A: 

Try reading up here: http://www.prototypejs.org/api/function/wrap

Ambrosia
i did but it's not particularly helpful
hatorade
It allows you to "build on existing functions by specifying before and after behavior, transforming the return value, or even preventing the original function from being called." I'm sorry but the example is as exemplifying as can be... you can pass additional arguments to your extended wrapper function and based on the parameters use the original function, or a modified form of it.
Ambrosia