2

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?

0

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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...

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.