jQuery Mobile - firing pageshow event only once - jquery-mobile

I am trying to execute a snippet of JS only once, after the page has completely loaded and JQM has taken care of all the ui modifications (i.e. listviews, buttons, etc.). I do want it to execute only on that page, and not on subsequent pages.
What I tried first, was pageshow
<script>
$('[data-role=page]').live("pageshow", function() {
alert("Ready!");
});
</script>
This has the problem that the function is now attached to the page div and gets executed every time any subsequent page gets shown. However, I only want this to be executed once, and only for the page that contains that JS snippet.
Is there a way to listen to the pageshow event, without actually attaching the function to it.
The only way I was able to do it was by binding and unbinding like this:
<script>
$('[data-role=page]').bind("pageshow.test", testfun);
function testfun() {
alert("Ready!");
$('[data-role=page]').unbind("pageshow.test", testfun);
}
</script>
But is there a more elegant way to do so?

jQuery has a one function to bind an event handler to be executed only once. Check the reference.

The pageinit event fires once per page just after the jQuery Mobile framework initializes its widgets; I think it may be what you're looking for.
pageinit
Triggered on the page being initialized, after initialization occurs.
We recommend binding to this event instead of DOM ready() because this
will work regardless of whether the page is loaded directly or if the
content is pulled into another page as part of the Ajax navigation
system.
Source: http://jquerymobile.com/demos/1.1.0-rc.1/docs/api/events.html
If you want to bind to a specific page and not the rest, then select only the page you want to alter... Here's an example:
<script>
$(document).delegate('#my-page-id', 'pageinit', function() {
alert("PageInit!");
});
</script>

Related

Apache Wicket and jQuery JavaScript in head section only loaded once

I face some strange issues when integrating jQuery with Wicket.
We load each content item as Panel in Wicket using Ajax. So it is a Single Page Application.
In the header of the Panel we add some JS, for example:
<script type="text/javascript">
$(document).ready( function() {
$('#example').dataTable( {
"sScrollY": "200px",
"bPaginate": false
} );
} );
</script>
However this code seems to be executed only the first time the Panel is loaded. If you reload the Panel into the application using Ajax, the code is not executed anymore.
I guess JS $(document).ready is only initialized one time, the second time you load the same JS into the browser $(document).ready is no more called.
Is there a workaround with Wicket for that issue?
Thanks!
Sebastian
document ready gets called only once, if you want to call on every load write the code as a seperate method and call it on success of every ajax load
I was able to resolve my issues given on this answer: http://mail-archives.apache.org/mod_mbox/wicket-users/201209.mbox/%3CCAAJwaYUSfoFZHVP4EXSxuw_Co-J0W6qvV1MR8wGERjfNzj2CxA%40mail.gmail.com%3E
You could add Renderhead().It executes whatever is being written inside it even on page refresh

How to use pageinit correctly?

I have a single file for each page and i am trying to implement the pageinit event handler on every page (I think what belongs strictly to one page, should be declared there) as shown below:
<body>
<div id="myPage" data-role="page">
<!-- Content here -->
<script type="text/javascript">
$("#myPage").live('pageinit', function() {
// do something here...
});
</script>
</div>
</body>
The event is bound properly to the page, so the code is executed but - now my problem - if i go to another page and return later on the pageinit event will be executed twice. I think that is because the .live method binds the pageinit event again to the page. But shouldn't the pageinit event only called once at page initialization? What I am missing here?
I solve the issue by passing the name of the event, in this case the "pageinit" instead of the handler.
<script defer="defer" type="text/javascript">
var supplier = null;
$("#pageID").die("pageinit"); //<--- this is the fix
$("#pageID").live("pageinit", function(event){
console.log("initialized - #(ViewBag.ID)");
supplier = new Tradie.Supplier();
supplier.Initialize("#(ViewBag.ID)");
});
Ref: http://www.rodcerrada.com/post/2012/04/26/jQuery-Mobile-Pageinit-Fires-More-Than-Once.aspx
I think its probably best to move your JavaScript code into another file as while your navigating around your site jQuery Mobile may cleanup (read: delete from DOM) that myPage page and therefore will have to load it in again and hense rerun that same block of code you defined and bind 2 listeners for the pageinit event.
Thats basically why they suggest using the live or on functions however it falls over if you include the binding code on the page ;)
However if you insist on having your code placed on a per page basis than use bind instead of live.
Ref: http://jquerymobile.com/demos/1.0/docs/pages/page-cache.html
jQuery Mobile therefore has a simple mechanism to keep the DOM tidy. Whenever it loads a page via Ajax, jQuery Mobile flags the page to be removed from the DOM when you navigate away from it later (technically, on the pagehide event).
I'm pretty sure they recommend binding pageinit to the document using on(). E.g.
$(document).on ('pageinit', '#myPage', function (event) {
instead of having the pageinit bound to the page, which is getting re-inited. In fact, I thought $(document).on() was the recommended way to bind events in jQuery, in general, now.
A quick workaround I have used is declaring a variable containing the handler function.
var handler = function() {
// your code
};
Then always use die() before binding the handler with live()
$( "#myPage" ).die( handler ).live( handler );
I'm sure this is not the intended usage by the authors, but it does the trick, you can leave your code within the page DIV.
$("#page1").live("pageinit", function () {
alert('pageinit');
$("#page1").die("pageinit"); //<--- prevent from firing twice on refresh
});

How to make getJSON to update correctly an element after page loaded in jQuery Mobile?

I'm trying to get a getJSON result to update an HTML element on page load, within a jquery mobile loaded website.
Now, I've read I should not rely on ready(), but bind to pageInit. So I tried, but it just won't work. I've tried many other events that could be logical to try within the API event documentation, without any success.
The closest I come to success is after the page is loaded, via ajax, if I refresh the page manually (with the browser's refresh button), getJSON does update the corresponding HTML element. And you guess, it's not what I want to achieve. Here is what the code looks like now, and where it is placed...
<div data-role="page">
<script>
$( '#pageContainer' ).live( 'pageinit',function(event){
//an alert() here does fire right before the page is shown in the browser
//here is the getJSON code.
});
</script>
Now, I need help to try to figure how to make it work. I only want an element X in the page to update with the text returned from a jSON when the page appears in the browser! Like a normal ready() function would have done !
(Maybe it is relevant to specify I'm running RC2 ?)
If you can't use JSONP here, have you tried setting a setTimeout()? You have to trigger a callback after the json object is loaded so timing is essential.

jQuery Mobile - Do something on page load

I want to do something every time a page loads. It's something that fixes the way the mobile site looks on different devices so it needs to happen on AJAX loads too.
At the moment, I've tried the traditional $(function(){ /*...*/ }); approach but that only works on the first load, and not subsequent AJAX loads.
I've been looking for the right event to bind to but I'm failing pretty hard.
You can use JQuery to bind to each "page" (div's set with the data-role=page attribute) and use the pageshow event (there are some others as well: pagebeforeshow, pagehide, pagebeforehide).
$(document).delegate('.ui-page', 'pageshow', function () {
//Your code for each page load here
});
http://api.jquerymobile.com/pageshow/
Note: this answer was written for jQuery Mobile 1.0.1, see the documentation link above for more information.
You can listen to the pageshow or pagecreate event and do your work there.
http://jquerymobile.com/test/docs/api/events.html

JqueryMobile page initialization function

I am using a master page on a JQuery-Mobile app that have few controller , and I want to set up a Javascript call to an initialize function on every page even when it loads through Ajax,
Iam sure there are few ways to do that, but whats the best approach and what would be the alternative to $(document).ready when the page is called through ajax instead of being directly loaded without that.
takepara's answer is correct, but...
If you want to modify the content of the page you will have to bind earlier.
Take a look at beforepagecreate event.
If your handler for this event returns false, then no JQM widgets and styles will be applied and you can work with it manually.
jQuery Mobile Docs - Events
$('div').live('pageshow',function(event, ui){
alert('This page was just hidden: '+ ui.prevPage);
});
or
$(document).bind("pageshow".function(){
// initialize code here
});

Resources