Go back to the main page

Using Prototype's invoke with a user defined function

 

Invoke is a fantastic mixin within Prototype.js; however, looking at the Prototype API, using invoke in a "custom" way is not explained. Meaning, all the examples are for either built-in Javascript methods(substring) or Prototype methods (camelize). What if you wanted to use your own user defined function with invoke? Let's try it.

function expandTagHelper(element){
 element.next().toggle();
 var html = element.innerHTML == '+' ? '-' : '+';
 element.update(html);
}

// This is what you want but it doesn't work 
$$('.tagExcerptShow').invoke('expandTagHelper');

What you must do is add this function to the Element object (making it one of its methods)

// My personal Element methods
Element.addMethods( {
 expandTagHelper: function(element){
   element.next().toggle();
   var html = element.innerHTML == '+' ? '-' : '+';
   element.update(html);
 }
});

// Works!
$$('.tagExcerptShow').invoke('expandTagHelper');
  • Pushed on 10/21/2010 by Christian