eric.itzhak
eric.itzhak

Reputation: 16072

How to override event and still preform the old one?

I'm looking for override event and still preform it's actions.

Meaning something like this:

var oldOnError = window.onerror;
window.onerror = function(msg, url, line) {
 oldOnError();
};

Now this will get executed however, onerror event could accept several arguments and I don't and can't know which are there.

So :

Upvotes: 1

Views: 819

Answers (2)

dfrishberg
dfrishberg

Reputation: 111

One thing you could do would be to use the apply method and the arguments variable:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

var oldOnError = window.onerror;
window.onerror = function(msg, url, line) {
    oldOnError.apply(window, arguments);
};

But as @Bruno says, only one argument should be passed to the handler anyway (the event).

Upvotes: 0

Bruno
Bruno

Reputation: 5822

Why not use addEventListener()

var listener = function(msg, url, line) {
 // your code
};

if (window.addEventListener) {
    window.addEventListener('error', listener, false);
} else if ( window.attachEvent ) { // for versions previous to IE9
    window.attachEvent( 'onerror', listener );
}

That way you do not override existing event listeners.

The other thing to note is that even though you specify 3 arguments your function is passed an event object when called. So really your function should be defined as follows.

var listener = function( event ) {
    // your code
}

Have a look at the MDN site here for more information

Upvotes: 1

Related Questions