Extend all prototypes

I have several jQuery prototype methods:

$.fn.one
$.fn.two
$.fn.three

      

Everyone has their own code and I want to add something to the end of all three. Let's say console.log ("done"). Is it possible?

+3


source to share


1 answer


You can re-name new functions that call their previous incarnations and then call them 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 jQuery prototype methods, you can iterate over $.fn

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]);
}

      

+3


source







All Articles