What is the best practice to not to override other bound functions to window.onresize?

不羁岁月 提交于 2019-11-30 17:25: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).

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);
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!