What is the best practice to not to override other bound functions to [removed]?

后端 未结 3 827
星月不相逢
星月不相逢 2021-01-03 23:36

How much I dig into JavaScript, I find myself asking that much. For example we have window.onresize event handler and if I say:

window.onresize          


        
相关标签:
3条回答
  • 2021-01-04 00:20

    Instead of replacing such a catch-all handler, you should just add a DOM 2 listener like this:

    window.addEventListener("resize", myResizeFunction);
    

    or in more details:

    if (window.addEventListener) {    // most non-IE browsers and IE9
       window.addEventListener("resize", myResizeFunction, false);
    } else if (window.attachEvent) {  // Internet Explorer 5 or above
       window.attachEvent("onresize", myResizeFunction);
    }
    
    0 讨论(0)
  • 2021-01-04 00:26

    You can save the old onresize function and call that either before or after your custom resize function. An example that should work would be something like this:

    var oldResize = window.onresize;
    
    function resize() {
        console.log("resize event detected!");
        if (typeof oldResize === 'function') {
            oldResize();
        }
    }
    window.onresize = resize;
    

    This method can have issues if there are several onresize functions. You could save the old onresize function as part of a closure and call the old one after your function.

    function addResizeEvent(func) {
        var oldResize = window.onresize;
        window.onresize = function () {
            func();
            if (typeof oldResize === 'function') {
                oldResize();
            }
        };
    }
    
    function foo() {
        console.log("resize foo event detected!");
    }
    
    function bar() {
        console.log("resize bar event detected!");
    }
    addResizeEvent(foo);
    addResizeEvent(bar);
    

    When you call addResizeEvent, you pass it a function that you want to register. It takes the old resize function and stores it as oldResize. When the resize happens, it will call your function and then call the old resize function. You should be able to add as many calls as you would like.

    In this example, when a window resizes, it will call bar, then foo, then whatever was stored in window.resize (if there was anything).

    0 讨论(0)
  • 2021-01-04 00:26

    One way of doing it is like this:

    function resize() { /* ... */ }
    
    var existing = window.onresize;
    window.onresize = function() {
        if (existing) {
            existing();
        }
        resize();
     }
    

    Or you can use something like jQuery which wraps all that stuff in a much simpler construct:

    $(window).resize(function() { /* ... */ });
    

    That automatically handles multiple handlers and stuff for you.

    0 讨论(0)
提交回复
热议问题