开发者

document.unload in JavaScript overrides or chains with the last definition?

I have been wondering this for sometime now.

If there is a function defined for body unload, and using JavaScript I do something like docume开发者_JAVA技巧nt.unload= function(), would the new definition of function be chained with the last one, or override it?

Is this behaviour different for browsers, or its the same across all browsers? If different, then why?

Can someone please shed light on this?


If you just assign a function to the property, then you will overwrite whatever is there already.

window.foo = 1;
window.foo = 2;

Foo is now 2 and you wouldn't expect it to be a chain of 1 then 2 if you tried to read it. Just because the browser looks at the property and tries to run a function there when an event happens doesn't change that.

You can do something along the lines of:

window.foo = aFunction;
oldFunc = window.foo;
window.foo = function () { oldFunc(); anotherFunc(); }

But I'd recommend using addEventListener and friends. Since we have to support Internet Explorer and have to deal with multiple event models I recommend using an abstraction layer as provided by any good JS library such as YUI or jQuery.


The process of hooking into 'unload' is tricky, and varies from browser to browser. You will definitely want to use some form of abstraction layer such as Prototype, jQuery, etc. For example, in jquery you would:

$(window).unload(function() {
  alert('Handler for .unload() called.');
});

alternatively, you can attach an event handler in a more traditional way by using

window.onbeforeunload = function(){  
    //handler 
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜