How to use pageinit correctly?

Dennis picture Dennis · Jan 9, 2012 · Viewed 12.7k times · Source

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?

Answer

Rod picture Rod · Apr 29, 2012

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