1

I want to override jQuery's hide() function on my object. I want it to call my onHide() function and then call original hide().

How to accomplish this?

The simplest code won't pass parameters I guess:

myobject.oldhide = myobject.hide;
myobject.onHide = function() {
   // something
};
myobject.hide = function() {
   this.onHide();
   this.oldhide();
}

jQuery's hide() accepts up to 3 parameters. Can I just define 3 of them?

myobject.oldhide = myobject.hide;
myobject.onHide = function() {
   // something
};
myobject.hide = function(a,b,c) {
   this.onHide();
   this.oldhide(a,b,c);
}

3 Answers 3

6

You can use .apply() to call the original:

this.oldhide.apply(this, arguments);

which will call oldhide with whatever argument list was passed to your own function, which need not have any declared parameters:

myobject.oldhide = myobject.hide;

myobject.onHide = function() {
   // something
};

myobject.hide = function() {
   this.onHide();
   this.oldhide.apply(this, arguments);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Doesn't this.oldhide.apply(this, arguments) will do the same as this.oldhide(arguments)?
@Dims, no. With the second, arguments is passed as the first (duration) parameter of jQuery's hide.
Ah, got it, thanks! And on general question, there is no other way to call old version of function other than keeping it in temporary variable?
@Dims no, the temporary variable is pretty much the only way.
2

Yes, the ones that are not passed in will just be undefined.

4 Comments

but the code will require changes if a new version of .hide() that takes four parameters comes along....
@Alnitak, only the function definition will change. The callers of the function don't have to change anything.
sure, but that's why arguments exists - you don't need to declare parameters a, b, c solely to pass them on verbatim to another function.
@Alnitak, agreed. The main reason would be if they were also used by the wrapper.
0

You could cache the old hide using $.proxy.

    myobject.oldhide = $.proxy(myobject.hide, myobject);
    myobject.onHide = function() {
       // something
    };
    //a, b, and c parameters don't have to be passed
    //but if they are they will be forwarded to the old hide.
    //Using $.proxy will preserve the way the old function takes parameters.
    myobject.hide = function(a, b, c) {
       this.onHide();
       this.oldhide(a, b, c);
    };

2 Comments

I don't understand, how parameters for hide() will pass to oldhide()? For example, if I write myobject.hide(12); from my point of view 12 will be lost since this.oldhide() does not pass it further. Is it true?
@Dims I have edited to include information about parameter passing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.