1

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?

kane
  • 5,465
  • 6
  • 44
  • 72
  • 1
    `pageshow` is deprecated and will be removed in 1.5, use `pagecontainershow` instead. – Omar May 09 '14 at 09:30
  • Try $(document).one('pageshow', '#dialogpage', function(event) { console.log('pageshow dialogpage'); }); – selva May 13 '14 at 08:34
  • Thanks for the reminder, Omar – kane May 13 '14 at 16:18
  • Thanks selva. I'll give this a try. I assume the .one() causes this event to fire once, so I'll see if it acts the way I need it to – kane May 13 '14 at 16:18
  • selva, the one() method seems to work. But I'm afraid I still don't understand the inner workings of jquery well enough to know whether using one() or unbind() will be a better approach... – kane May 14 '14 at 02:43
  • If the dialog is an external file, e.g. Dialog.html and you have JS code embedded within it, it will be loaded each time you open the dialog resulting in multiplied `pageshow` event. `$(document).off("pageshow", "#dialog").on("pageshow", "#dialog", function () { ... });`. – Omar Jun 16 '14 at 00:26

1 Answers1

0

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?

Maurice Perry
  • 32,610
  • 9
  • 70
  • 97