如果事件至少调度了一次,则立即执行事件侦听器代码

时间:2018-06-29 09:42:26

标签: javascript events

// Event listener registered before event dispatched.
document.addEventListener('myappready', function (e) {
 console.log("I am always on time :) ");
});

// Dispatch the event.
document.dispatchEvent(new Event('myappready'));

// Event listener registered after event dispatched.
document.addEventListener('myappready',  function() {
   console.log("I am always late :( ");
});

它给出输出:

I am always on time :)

但是我想要输出:

I am always on time :)
I am always late :(

1 个答案:

答案 0 :(得分:1)

您可以通过为addEventListener实现包装器来执行此操作,然后可以跟踪事件是否已经触发,如果是,则立即调用回调。

例如

function myAppReady(cb) {
  if (!myAppReady.ready) {
    document.addEventListener('myappready',function () {
      myAppReady.ready = true;
      cb();
    });
  } else cb();
}
myAppReady.ready = false;


// On time..
myAppReady(function () {
  console.log("I am always on time :) ");
});

// Dispatch the event.
document.dispatchEvent(new Event('myappready'));

// Event listener registered after event dispatched.
myAppReady(function() {
   console.log("I am always late :( ");
});