7

I can not seem to have the receiver event listener removed. Given the code below the console will continue printing "hi" endlessly.

Receiver:

window.addEventListener("message", function(e){
       console.log('hi');
       window.removeEventListener("message", function(e){}, false)
}, false);

Sender :

var emiter = setInterval(function(){
            console.log('sending message');
            window.parent.postMessage( messageData, "*" );
        }, 1000);

Is there a way around this ?

silkAdmin
  • 4,640
  • 10
  • 52
  • 83

1 Answers1

20

I believe in order to remove the listener you have to have a reference to the same function so like this:

var f = function(e){
  console.log('hi');
  window.removeEventListener("message", f, false);
}
window.addEventListener("message", f);

So the reason your's doesn't work is because it doesn't have a reference to that function as a listener.

ars265
  • 1,949
  • 3
  • 21
  • 37
  • 1
    Yea right too much jquery i forgot about that, thanks.. though in that case how do can i pass parameter to my callback, other than the event object? – silkAdmin Oct 26 '12 at 20:41
  • I don't believe you can, you just need to get values after. – ars265 Oct 26 '12 at 21:02
  • this may help you in some way but I still don't think it's entirely possible to add parameters to pass to the function. http://stackoverflow.com/questions/256754/how-to-pass-arguments-to-addeventlistener-listener-function – ars265 Oct 26 '12 at 21:09