Is this your first visit? You may want to subscribe to the feed.

Adding DOM methods with Prototype

I just discovered that prototype has a really cool way to add methods to all instances of any tag. Simply call Element.addMethods(tagname, methods). For example, here’s how I added a request method to anchors, which will just make an ajax call for the anchor’s href:

if (!window.Anchor) { var Anchor = new Object(); }

Anchor.Methods = {
  request: function(anchor, options) {
    anchor = $(anchor)
    options = Object.extend({method: 'get'}, options || {});
    return new Ajax.Request(anchor.readAttribute('href'), options);
  }
}
Element.addMethods('a', Anchor.Methods);

So now I can go through and hijack links with a specific tag name and just call request() on them:

$$('a.jax').each(function (link) {
  link.observe('click', function(event) {
    link.request({evalScripts: true});
    Event.stop(event);
  });
})
Code: javascript, prototype Jul 11, 2007 ● updated Jul 11, 2007 0 comments

Speak your mind:

*

*


* I hate spam and will never sell or publish your email address.

(You may use textile in your comments.)

Subscribe

Browse by Tag