简体   繁体   English

如何向window.onunload添加更多功能?

[英]how to add more functions to window.onunload?

suppose I have some javascript which says: 假设我有一些javascript说:

window.onunload=some_jsfunction();

how can I add another function to this handler? 如何向此处理程序添加其他函数? something like this: 这样的事情:

window.onunload=some_jsfunction() + another_jsfunction();

The first and foremost way: addEventListener : 第一个也是最重要的方式: addEventListener

window.addEventListener('unload', function () { /* Do things. */ });
window.addEventListener('unload', function () { /* Do other things. */ });

Another way is too create a new event handler with a call to the old handler from it, then overwrite the old handler. 另一种方法是创建一个新的事件处理程序,从中调用旧的处理程序,然后覆盖旧的处理程序。 I can imagine a situation where it could be useful, but not with DOM events: 我可以想象它可能有用的情况,但不是DOM事件:

var onUnload = function () {
    /* Do things. */
};

var oldOnUnload = onUnload;

onUnload = function () {
    oldOnUnload();
    /* Do new things. */
};

The most advanced way is creating your own observer on top of the DOM's observer (this is what frameworks like Mootools do internally). 最先进的方法是在DOM的观察者之上创建自己的观察者(这就是Mootools在内部做的框架)。 It can be helpful in the long term; 从长远来看,这可能会有所帮助; for example, to add event namespaces. 例如,添加事件命名空间。

var handlers = [];

window.onunload = function () {
    handlers.forEach(function (fn) { fn(); });
};

handlers.push(function () { /* Do things. */ });
handlers.push(function () { /* Do other things. */ });

Call a function on window.onunload and call your function in that function. window.onunload上调用一个函数并在该函数中调用你的函数。 Some thing like this 有点像这样

window.onunload = callFunctions;

While your callFunctions look like 虽然你的callFunction看起来像

function callFunctions() {
  someFunction();
  anotherFunction();
}

The jQuery library uses a approach event listeners for the document ready function are put in a callback list and the functions get called when the ready event is fired. jQuery库使用方法事件监听器将文档就绪函数放入回调列表中,并在触发ready事件时调用函数。 For your problem this could be implemented somehow like this 对于你的问题,这可以通过某种方式实现

    onunloadList = new Array();
    function addOnUnloadHandler( fn ) {
      // Add the callback
      onunloadList.push( fn );
    }

    function handleOnUnloadHandlers( fn ) {
      for (i=0;i<onunloadList.length;i++) {
        var fn = onunloadList[i];
        fn();
      }
    }

    window.onunload = handleOnUnloadHandlers();

In general I'd recommend to use some kind of framework like jQuery because that has such mechanism built in. And code you don write you don't have to maintain. 一般来说,我建议使用某种类型的框架,比如jQuery,因为它内置了这样的机制。而你编写的代码则不需要维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM