Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Mobile - firing pageshow event only once

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?

like image 444
Steve Avatar asked Dec 21 '22 00:12

Steve


1 Answers

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

like image 87
Ekin Koc Avatar answered Jan 06 '23 00:01

Ekin Koc