Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Mobile: inline data-role="page" javascript being retain when page is released from DOM?

Using this call <a href="deleteDialog.html" data-rel="dialog" data-transition="pop" data-role="button" id='deleteDialog'>Delete</a> to get the following dialog page:

<div data-role="page" id="deleteCompanyDialog">
<script type="text/javascript">

$("#deleteButton").live("click", function() {
        alert("this alert increments");

});

</script>

    <div data-role="header" data-theme="d">
        <h1>Dialog</h1>

    </div>

    <div data-role="content" data-theme="c">
        <h1>Delete Company</h1>
        <p id="message"></p>
        <a data-role="button" data-theme="b" id="deleteButton" >Sounds good</a>       
        <a href="company.jsp" data-role="button" data-rel="back" data-theme="c">Cancel</a>    
    </div>
</div>

seems to retain the live("click".. binding from any previous calls to this dialog and then binds the live call again. So if I call the page 4 separate times, on the forth dialog page call it will popup 4 alert screens. Is there a way to have the javascript still be within data-role="page" so it can load with ajax but not increment the "live" binding. I tried $("#deleteCompanyDialog").live("pagecreate"... as well as pageload (a long shot) which does not work either.

Help would be greatly appreciated.

like image 910
Greg Avatar asked Jan 19 '12 17:01

Greg


1 Answers

Instead of using .live(), use .bind() and place your JavaScript in a delegated event handler:

<div data-role="page" id="deleteCompanyDialog">

    <div data-role="header" data-theme="d">
        <h1>Dialog</h1>

    </div>

    <div data-role="content" data-theme="c">
        <h1>Delete Company</h1>
        <p id="message"></p>
        <a data-role="button" data-theme="b" id="deleteButton" >Sounds good</a>       
        <a href="company.jsp" data-role="button" data-rel="back" data-theme="c">Cancel</a>    
    </div>
<script type="text/javascript">

$(document).delegate("#deleteCompanyDialog", "pageinit", function() {
    $("#deleteButton").bind('click', function () {
        alert("this alert DOES NOT increment");
    });
});

</script>
</div>

This is like using $(function () {}); but for jQuery Mobile. The pageinit event will fire when the page is initialized (happens once per pseudo-page) and the .bind() function call will only bind to elements present in the DOM. When you use .live() it doesn't bind to the actual element, it binds to the document element, which does not get removed when you navigate away from the dialog (so each time you show the dialog you add another delegated event handler).

like image 107
Jasper Avatar answered Sep 18 '22 02:09

Jasper