Jquery off() on element that doesn't exist anymore

167 Views Asked by At

I have an iframe that content is somehow loaded with ajax, not with content Location. This is WordPress customizer preview iframe. It's something like jquery mobile, the page in iframe flashes and new content is loaded. That said, I can't use load and unload events for this iframe, and I have to bind a click event listener to its contents.

So I came up with an idea to emulate load event. I will add javascript to the page that is loaded in an iframe and it executes iframe parent function when document is ready, the function then can bind the event listener to the new iframe contents.

But how can I unbind it, so I don't get any memory leaks? I tried adding an event listener on unload in the loaded page, but strangely, the unload event runs after the next page is already loaded, so the contents which have an event listener are already gone.

So basically there's no way I can off() the iframe contents before they disappear from the DOM. I have to off() them when they are gone, how can I do that?

Edit: I think I got it solved. Just store the contents in a variable. It seems like memory is not leaking anymore.

var iframeContents;

this.iframeLoadEmulation = function () {
   if (typeof iframeContents !=='undefined') {
      console.log('unbinding old content');
      iframeContents.off();
      iframeContents=null;
   }
   iframeContents=$('#customize-preview').find('iframe').contents();
   iframeContents.on('click', function(){ console.log('click'); });
}

Did I get that right? Is it a good code or is there a better way to do it?

0

There are 0 best solutions below