Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend all prototypes

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?

like image 610
Ryan Mulready Avatar asked Mar 26 '26 20:03

Ryan Mulready


1 Answers

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]);
}
like image 183
Frédéric Hamidi Avatar answered Mar 28 '26 08:03

Frédéric Hamidi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!