What is the best practice to not to override other bound functions to window.onresize?
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.onresi开发者_开发百科ze = resize;
function resize()
{
console.log("resize event detected!");
}
Wouldn't that kill all other functions which is connected to the same event and just log my message in console?
If so I think there should be another notifier which tells me about window resize event - or a workaround maybe - without overriding other functions which are bound to same event.
Or am I totally confused by its usage?
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);
}
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).
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.
精彩评论