0

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?)

Tony Stark
  • 24,588
  • 41
  • 96
  • 113
  • proceed is the original function (not direct though). eachWord is the boolean argument being passed in from the example. If eachWord is true then the new function defined will be run, else the original function, proceed(), will be called. The confusion here might be because they have called it proceed() when it really doesn't matter what its called... it will still link to the original capitalize function. – AmbrosiaDevelopments Nov 20 '09 at 03:51
  • ah, so it passed the 'capitalize' function in as the 'proceed' method in the wrapper? – Tony Stark Nov 20 '09 at 03:58
  • indeed :) but beware it isn't the actual prototype function. There are some layers of indirection in there. – AmbrosiaDevelopments Nov 20 '09 at 04:09

1 Answers1

0

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

AmbrosiaDevelopments
  • 2,576
  • 21
  • 28
  • i did but it's not particularly helpful – Tony Stark Nov 20 '09 at 03:32
  • 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. – AmbrosiaDevelopments Nov 20 '09 at 03:39