You are browsing the archive for multiple.

[jQuery Mobile] Avoiding multiple pageinit executions for separate pages

December 24, 2013 in jQuery, jQuery Mobile, mobile

One of the common problems in jQuery mobile when navigating to a separate page in a separate HTML file is that he “pageinit” event will be triggered each time page is visited. The problem becomes severe when you find that each time you visit the separate page, your “pageinit” event handler is registered +1 more time which makes a great hassle because of the multiple event binding.

Let’s see an example to understand the problem, assume that we have a separate page called “pageA” which includes a JavaScript file that defines “pageinit” event handler as follows:

$(document).on("pageinit", "#pageA", function(e) {
    e.preventDefault();
	
    //Initialization can be done here ...
});

If you navigate from any page to “pageA”, you will find that in everytime you visit this page, your “pageinit” event handler will be registered and executed, which means that if you visit the page for the second time, you will find “pageinit” event handler executed twice and for the third time, you will find it executed 3 times and so on.

In order to resolve this issue, you will need to un-register the “pageinit” event as follows using $(document).off().

$(document).on("pageinit", "#subscriptionView", function(e) {
    e.preventDefault();
	
    //Initialization can be done here ...
	
    $(document).off("pageinit", "#subscriptionView");
});

Doing this workaround makes “pageinit” event handler executing only once each time the page is loaded.

P.S. This behavior does not happen in jQuery mobile when you follow the single HTML file approach which includes all the application pages.

Skip to toolbar