views:

34

answers:

2

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 = 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? Thanks.

+2  A: 

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.

Dean Harding
cool, thanks for the answer. Do you have any clue how jquery does that, bc what i actually want to learn is that?
KakambaWeb
@KakambaWeb: jQuery works by keeping it's own internal list of "attached" handlers and then override the onresize handler with one that loops through that list calling them one-by-one.
Dean Harding
@Dean, thanks again.
KakambaWeb
+2  A: 

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

Buddy
nice one `Buddy` thanks :)
KakambaWeb