I have a few jQuery prototype methods:
$.fn.one
$.fn.two
$.fn.three
Each has their own code and I want to add something to the end of all three. Lets say console.log('done'). Is this possible?
You can rebind the names to new functions that call their previous incarnations, then invoke console.log().
Something like:
$.each(["one", "two", "three"], function(index, name) {
var originalMethod = $.fn[name];
$.fn[name] = function() {
var result = originalMethod.apply(this, arguments);
console.log(name + "() done.");
return result;
};
});
If you want to apply this behavior to all the methods in jQuery's prototype, you can iterate over $.fn itself and only process functions:
for (var name in $.fn) {
// Create a new scope so 'originalMethod' is still bound to the
// right method by the time our new '$.fn[name]()' is invoked.
(function(originalMethod) {
if ($.isFunction(originalMethod)) {
$.fn[name] = function() {
var result = originalMethod.apply(this, arguments);
console.log(name + "() done.");
return result;
};
}
})($.fn[name]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With