Nurullah Yel
Nurullah Yel

Reputation: 73

Extending jQuery addClass to accept callbacks - how does it work?

I am fairly new to jQuery and were looking for a way to extend addClass to accept callbacks. I found this solution here. Here is the code part that does do the magic:

var oAddClass = $.fn.addClass;
$.fn.addClass = function () {
    for (var i in arguments) {
        var arg = arguments[i];
        if ( !! (arg && arg.constructor && arg.call && arg.apply)) {
            arg();
            delete arg;
        }
    }
    return oAddClass.apply(this, arguments);
}

Can someone explain what happens here? I've got basic knowledge of programing terminology and I've already used jQuery for simple stuff like scroll-over ads.

Sincerely,

Nunu

Upvotes: 0

Views: 353

Answers (1)

Shilly
Shilly

Reputation: 8589

Basically it loops over all the arguments addClass was called with. If that argument is a function (found out by duck typing that the argument has a constructor and call/apply methods), it will call that function and remove it from the arguments arraylike object.

Lastly the remaining arguments, (the non-functions) are apply'ed onto the element by using the reference to the original addClass function (oAddClass), so that the real class strings are also added to the element.

As a sidenote, why would you have need for callbacks on setClass, since it's not async.

Upvotes: 2

Related Questions