Rails introduce a pattern called alias\_method\_chain in 2006. The general idea is you want to add something to an existing method, but you don’t want to monkey patch the whole method.
I found myself wanting this functionality in JavaScript. My use case was adding a callback to the Ajax.Autocompleter in script.aculo.us. Here is how I solved it.
This is the code that defines aliasMethodChain on Object.
Object.extend(Object, {
aliasMethodChain: function(object, target,
feature, implementation) {
object[target + "Without" +
feature.charAt(0).toUpperCase() +
feature.substring(1)] = object[target];
object[target] = implementation;
}
});
And here I am using the aliasMethodChain.
Object.aliasMethodChain(Autocompleter.Base.prototype,
"selectEntry", "selectCallback", function() {
this.selectEntryWithoutSelectCallback();
this.options.onSelect ? this.options.onSelect() : null;
});
Nothin’ to it. Now I can pass onSelect into the options of any autocompleter and it will be called when the user makes a selection.
ziz5u707jzuhsppv