Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for multiple Events

I'm currently developing an app mainly for self-education purposes and since I'm still not completely used to js I could use some help for my problem:

In my app I'm using a Javascript library (jqMobi) which is used for DOM manipulation, page transitions, ajax calls etc and I'm also using phonegap to access device features such as the geolocation.

When I start up my app I want to get the geolocation of the device, send an ajax (jsonp) request to my server (including the geolocation of the device) which returns an array of JSON objects which I will use to build up a list.

Before I can get the geolocation I need to wait for phonegap to load. And before using jqMobi to make the ajax call and handle the response I need to wait for it to load as well.

So I basically have to events im listening to

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

How do I execute a function as soon as both of these events have fired and not before?

If I'd use jQuery I'd make use of its $.Deferred objects and its When ... Then Function but since I don't have access to these I'm looking for an alternative.

like image 382
marius2k12 Avatar asked Dec 19 '12 20:12

marius2k12


People also ask

How does Python handle multiple events?

We simply use if/elif statements. You can add as many if/elif statements as you want or need to check for various events and accordingly take action for each of these events that a user does. This is all that is required to check for multiple events in Python with OpenCV.


1 Answers

At first blush, something like this would 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 is not extensible (what if you want a third event to wait on?). A counter would 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!
  }
}

Is more extensible, but that assumes that the events only fire once. Either way, these are the primatives that can control the type of flow control you are asking for, and everything else is (for the most part) a higher level abstraction on these two.

like image 114
syazdani Avatar answered Nov 10 '22 00:11

syazdani