开发者

Safely using hook events in JavaScript

开发者 https://www.devze.com 2023-03-11 09:22 出处:网络
In source code here http://www.daftlogic.com/sandbox-javascript-slider-control.htm There is these instructions:

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

There is these instructions:

// safely hook do开发者_C百科cument/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?


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消