Reputation: 5180
I'm currently building a simple jQuery Mobile application. Currently, if I want to do some stuff either before or after page load, I use the following call hook:
When page is shown (e.g. to insert data/templates):
$(window).on('pageshow', function() {
if ($('#pageId').length > 0) {
doStuff();
}
});
If the user moves to a new page (and I want to save some values):
$(document).delegate('#pageId #buttonNext', 'click', function() {
doStuff();
});
I have two questions:
Is there a better and more elegant way to do this (and I am sure there is)?
On mobile devices (especially iOS Safari) each time the app is re-opened after safari has been closed, the pageshow
method is fired again so for example are re-entered into the already fully built up page. Is there a way to prevent that behaviour?
Upvotes: 1
Views: 2036
Reputation: 57309
If I understood you correctly you want a event that will trigger only once and a better way to save some values during the page transition.
There are several page events that will trigger only once during the app life, it doesn't matter if page is visited several times.
First two to mention are pagebeforecreate and pagecreate, those two events will trigger only once before and during the page creation. This is also an excellent opportunity to add dynamically generated content because jQuery Mobile will enhance its content a little bit further down the line.
Third page event is called pageinit and it a real counterpart to classic jQuery document ready. Like previous 2 events mentioned it will trigger only once but this is also a moment when jQuery Mobile content is about to be enhanced, so every dynamic content added at this point must be manually enhanced. This event is also excellent for event binding, because unlike pageshow, when binding events in pageinit
you don't need to worry about multiple event binding.
Pageshow
should be used ONLY when working with plugins that require correct page height because page height has real value only when page is shown. This is important for plugins like photo galleries, carousels, basically everything that handles pictures.
If you want to find more about page events take a look here. Also there you will be able to find 3 different solutions of passing / storing data between page transitions.
Upvotes: 2