Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Overloading on jQuery Object

I'm trying to add a method to a jQuery object that has the same name (but different parameter set) as another method.

What I've got so far:

jQuery.fn.insertBefore = function(elem, duration)
{
    this.css("display", "none");
    this.insertBefore(elem);
    this.toggle(duration);
}

However, this code (specifically the this.insertBefore(where); line) calls this same function, and not the jQuery insertBefore() function, as desired. What do I need to do in order to add this function to the jQuery object, and have it overload (not overwrite) the existing function?

EDIT: Solution

(function ($)
{
    var oldInsertBefore = $.fn.insertBefore;
    jQuery.fn.insertBefore = function(elem, duration)
    {
        if (duration === undefined)
        {
            oldInsertBefore.call(this, elem);
            return;
        }

        this.css("display", "none");
        this.insertBefore(elem);
        this.toggle(duration);
    }
})(jQuery);
like image 920
Patrick Perini Avatar asked Dec 27 '11 16:12

Patrick Perini


2 Answers

You back up original function before overwriting. Something like this:

(function($){
    var oldInsertBefore = $.fn.insertBefore;
    jQuery.fn.insertBefore = function(elem, duration)
    {
        oldInsertBefore.apply(this, arguments);
        this.css("display", "none");
        this.insertBefore(elem);
        this.toggle(duration);
    }
})(jQuery);
like image 176
Sergio Tulentsev Avatar answered Oct 20 '22 00:10

Sergio Tulentsev


you can use $.sub()

(function($){
    var sub$ = $.sub();

    sub$.fn.insertBefore = function(where, duration) {
       this.css("display", "none");
       this.insertBefore(where);
       this.toggle(duration);
    }

    /* you can use this plugin in this scope or you could also
       return sub$ and call the plugin outside */
})(jQuery);

description of $.sub():

Creates a new copy of jQuery whose properties and methods can be modified without affecting the original jQuery object.

from http://api.jquery.com/jQuery.sub/

like image 22
Fabrizio Calderan Avatar answered Oct 19 '22 23:10

Fabrizio Calderan