user310291
user310291

Reputation: 38180

Safely using hook events in JavaScript

In source code here http://www.daftlogic.com/sandbox-javascript-slider-control.htm

There is these instructions:

// safely hook document/window events
if (document.onmousemove != f_sliderMouseMove) {
window.f_savedMouseMove = document.onmousemove;
document.onmousemove = f_sliderMouseMove;
}

I don't understand what it does and why it would be safer to do that this way, does someone understand?

Upvotes: 2

Views: 3482

Answers (3)

Felix Kling
Felix Kling

Reputation: 816384

It might be that some other code already assigned an event handler to document.onmousemove. The problem with this method, as opposed to addEventListener, is that only one function can be assigned to element.onXXXX. Thus, if you blindly assign a new event handler, an already existing one might be overwritten and other code might break.

In such a case, I would write:

if (document.onmousemove) {
    (function() {
         var old_handler = document.onmousemove;
         document.onmousemove = function() {
            old_handler.apply(this, arguments);
            f_sliderMouseMove.apply(this, arguments);
         };
    }());
}
else {
    document.onmousemove = f_sliderMouseMove;
}

This way it is ensured that both event handlers are executed. But I guess that depends on the context of the code. Maybe f_sliderMouseMove calls window.f_savedMouseMove anyway.

Upvotes: 3

Jacob Mattison
Jacob Mattison

Reputation: 51052

It appears that this code is storing the function that is currently executed on a mouse move, before setting the new one. That way, it can presumably be restored later, or delegated to, if need be. This should increase compatibility with other code or frameworks.

Upvotes: 1

James Gaunt
James Gaunt

Reputation: 14783

It is just saving the current hook, presumably so it can call it at the end of its own hook method.

It avoids stamping on some other codes hook that was already set up.

You would expect the hook code to be something like:

f_sliderMouseMove = function(e) {
   // Do my thing

   // Do their thing
   window.f_savedMouseMove();
}

[obligatory jquery plug] use jquery events and you can ignore problems like this...

Upvotes: 1

Related Questions