等待多个事件

mar*_*k12 8 javascript dom-events

我目前正在开发一个主要用于自我教育目的的应用程序,因为我还没有完全习惯于js,我可以使用一些帮助解决我的问题:

在我的应用程序中,我使用的是一个javascript库(jqMobi),用于DOM操作,页面转换,ajax调用等,我还使用phonegap访问设备功能,如地理位置.

当我启动我的应用程序时,我想获取设备的地理位置,向我的服务器发送ajax(jsonp)请求(包括设备的地理位置),该请求返回一个json对象数组,我将用它来构建一个列表.

在我获得地理位置之前,我需要等待phonegap加载.在使用jqMobi进行ajax调用并处理响应之前,我需要等待它加载.

所以我基本上要听的事件

document.addEventListener("DOMContentLoaded",execute_this,false);  //jqMobi is now ready
document.addEventListener("deviceready", execure_sth, false); //Phonegap is now ready
Run Code Online (Sandbox Code Playgroud)

一旦这两个事件都被触发而不是之前,我该如何执行一个函数?

如果我使用jQuery,我会使用它的$ .Deferred对象及其When ... Then Function,但由于我无法访问这些,我正在寻找替代方案.

在此先感谢您的帮助!

sya*_*ani 21

乍一看,这样的东西肯定会起作用:

var executed_this = false, executed_sth = false;

function execute_this() {
  executed_this = true;
  combined_execution();
}

function execute_sth() {
  executed_sth = true;
  combined_execution();
}

function combined_execution() {
  if (executed_this && executed_sth) {
    // magic!
  }
}
Run Code Online (Sandbox Code Playgroud)

但是不可扩展(如果你想要第三个事件等待怎么办?).一个计数器可以工作:

var wait_on = 2;

function execute_this() {
  combined_execution();
}

function execute_sth() {
  combined_execution();
}

function combined_execution() {
  wait_on--;
  if (wait_on === 0) {
    // magic!
  }
}
Run Code Online (Sandbox Code Playgroud)

更具可扩展性,但假设事件只触发一次.无论哪种方式,这些都是能够控制您所要求的流量控制类型的原型,而其他一切(在大多数情况下)是这两者的更高级别的抽象.


Tan*_*ope 14

您可以使 Promise 在事件触发时解决,并等待它们都准备就绪。

var dcl = new Promise(function(resolve) {
    document.addEventListener("DOMContentLoaded",resolve,false);
})
var deviceready = new Promise(function(resolve) {
    document.addEventListener("deviceready", resolve, false);
})

Promise.all([dcl, deviceready]).then(function() {
    //both are ready
});
Run Code Online (Sandbox Code Playgroud)


pps*_*ith 1

尝试这个,

document.addEventListener("DOMContentLoaded",execute_this,false);
function execute_this(){
document.addEventListener("deviceready", execure_sth, false);
}
function execute_sth(){
//your code here
}
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的帮助。但有一个问题:如果 deviceready 事件发生在 DOMContentLoaded 之前,会发生什么情况?它还会调用execute_sth吗? (3认同)