Waiting for multiple events

I am currently developing the application mainly for self-learning purposes, and since I'm still not quite used to js, ​​I can use some help to solve my problem:

In my application, I use the Javascript library (jqMobi), which is used to manipulate the DOM, page transitions, ajax calls, etc., and I also use phonegap to access device features such as geolocation.

When I launch my application, I want to get the device’s geolocation, send an ajax (jsonp) request to my server (including the device’s geolocation), which returns an array of JSON objects that I will use to create the list.

Before I can get geolocation, I need to wait for the phone gap to load. And before using jqMobi to call ajax and process the response, I need to wait for it to load.

So I basically need the events that I listen to

document.addEventListener("DOMContentLoaded",execute_this,false); //jqMobi is now ready document.addEventListener("deviceready", execure_sth, false); //Phonegap is now ready 

How to execute a function as soon as both of these events have worked, and not earlier?

If I used jQuery, I would use its $.Deferred objects and its When ... Then function, but since I do not have access to them, I am looking for an alternative.

+8
source share
3 answers

Try it,

 document.addEventListener("DOMContentLoaded",execute_this,false); function execute_this(){ document.addEventListener("deviceready", execure_sth, false); } function execute_sth(){ //your code here } 
+1
source

Blush first, something like this will definitely work:

 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! } } 

But not expanding (what if you want the third event to wait?). The counter will work:

 var wait_on = 2; function execute_this() { combined_execution(); } function execute_sth() { combined_execution(); } function combined_execution() { wait_on--; if (wait_on === 0) { // magic! } } 

More extensible, but assumes that events fire only once. In any case, these are primitives that can control the type of flow control that you request, and everything else (for the most part) is a higher level abstraction for the two.

+20
source

You can give Promises that are resolved when events occur, and wait until they are both ready.

 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 }); 
+1
source

All Articles