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);
});
})
This content is open source.
Suggest Improvements.