Is it necessary to unbind pageshow events after closing dialog?

477 Views Asked by At

I'm finding something that is slightly annoying and want to make sure I'm not doing anything blatantly wrong. I'm using jquery-mobile 1.4.

I have a mainpage.html that calls a dialogpage.html modeled as a dialog. The dialogpage has a <div data-role="page" id="dialogpage" data-dialog="true">.

The dialogpage also has a pageshow event attached to the div page like so

$(document).on('pageshow', '#dialogpage', function(event) {
  console.log('pageshow dialogpage');
});

What I'm finding is that each time I open this dialogpage, an additional pageshow event is called. What I mean by this is that the first time I open the dialog, the console prints "pageshow dialogpage" once. The second time I open the dialog, it prints it twice. The third opening of the page prints it thrice, etc

It seems as if the pageshow event is being attached again and again each time I open the page. In some sense, this makes sense, but it seems rather annoying to deal with.

My solution is to add an unbind event like so:

$(document).on('pagehide', '#dialogpage', function(event) {
    console.log('pagehide dialogpage');
    $(document).unbind('pageshow');
    $(document).unbind('pagehide');
  });

This seems to keep "pageshow dialogpage" from being printed multiple times. But does this mean I need to unbind all events in a dialog page?

Am I doing something wrong?

1

There are 1 best solutions below

1
On

Since your binding your events with on, I would unbind them with off. And I would also specify the filter (#dialogpage):

$(document).off('pageshow','#dialogpage');
$(document).off('pagehide','#dialogpage');

UPDATE:

Oh, and do you remove the dialog from the dom?