Sulot
Sulot

Reputation: 514

How to handle nested event listeners javascript? (not about nested html elements)

I need a function to trigger only after 2 events. First event is onload, and second is onmessage coming from an iframe.

If onload and onmessage=="something"=> trigger that. Otherwise => something else.

However, it seems that onload is executed before my onmessage. SO i need the 2 event to be nested. (Or not?)

Shoud I do like this:

     document.getElementById("myiframe").addEventListener("load", iframeLoaded, false);

        function iframeLoaded(){
        window.top.addEventListener("message", WhatisTheMessage, false);
        }

    function WhatisTheMessage(event){
 window.top.removeEventListener("message", WhatisTheMessage, false);

    if(event.date=="something"){//do something}
    else if(event.date=="somethingelse"){//do somethingelse}
    }

Does it seem correct? The problem that appear to me is that if "message" is arriving before (I think it is not is not possible), I don't listen to it.

Upvotes: 0

Views: 1674

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138297

window.addEventlistener("load",test,false);
window.addEventlistener("message",test,false);
var counter=0;
 function test(event){
  counter++;
  if(counter==2){
   //two event listeners called
  }
 }

Upvotes: 1

Related Questions