开发者

Adding a javascript function call to an event (such as 'window.resize') instead of overwriting what is already there

Is there a way to tell the browser to run an addtional java script function on an event such as 'window.resize' instead of overwriting what is already there?

Using jquery's

$(window).resize(<something>);

Seems to replace what is already there. Is开发者_JS百科 there a way to tell it to do something in addition? Is this a poor design / wrong way to do it?


I wouldn't think that jQuery would break what's there, but you could wrap the functions in a single function:

    // if a function already exists...
if( window.onresize ) {
    var prev_func = window.onresize;  // cache the old function

    window.onresize = function( event ) {  // new function for resize

        prev_func.call( window, event );  // call the old one, setting the
                                          //  context (for "strict mode") and 
                                          //  passing on the event object

        // call your code or function

    };
}

EDIT: Fixed it to use onresize instead of resize.

EDIT2: Missed one! Fixed.


If you're using jQuery to bind all event handlers, then you're not breaking anything. jQuery supports multiple handlers for same event.

But if other code (not using jQuery) binds to the event, then you'll overwrite handler with your statement. The solution will be: always use jQuery for event binding or try to save old handler (see patrick dw's answer).


See element.addEventListener (element.attachEvent in IE 8 and under):

// Standards
if (window.addEventListener){
    window.addEventListener("resize", callOnResize, false); 
// IE 8 and under
} else if (window.attachEvent){
    window.attachEvent('resize', callOnResize);
}

function callOnResize() {
  console.log("resized");   
}

Keep in mind this is pure JavaScript—jQuery (and pretty much any big JS library) has a method to handle creating standards and IE handlers without you needing to write each. Still, it's good to know what's happening behind the scenes.


jQuery and all other frameworks supporting custom events attach a function to the event of the elem (or observe it). That function then triggers all functions that have been bound (using bind) for a specific event type.

domelement.addEventListener does not override an other function and your function added can't be removed by other (bad) javascript, except when it would know the exact footprint of your function.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜