I have two jquery mobile pages, each in a separate HTML document. When I link to the second document, the pagecreate event fires every time. This has the annoying side effect of initialising the handlers multiple times - once for every time the page has been created.
However, I have noticed that there is a difference between -
$('#btn').on("click", function () {...});
and
$(document).on("click", "#btn", function () {...});
In the first case, the event handler is called only once (which is what I want), but in the second case, it is called once for every time the handler has been initialised. Can someone explain why this is please, and is it safe to rely on the first case to ensure that the handler is only called once?
Here is the initial page:
<body>
<div id="firstpage" data-role="page">
<a href="testpageinit_2.php" id="goto" class="ui-btn">Page 2</a>
</div>
</body>
and the second page:
<body>
<div id="secondpage" data-role="page">
<a href="#" id="btn" class="ui-btn">Click Me</a>
<a href="firstpage" id="btnback" class="ui-btn" data-rel="back">Back</a>
</div>
</body>
My js looks like this:
$(document).on("pagecreate", "#firstpage", function () {
alert("First page created");
});
$(document).on("pagecreate", "#secondpage", function () {
alert("Second page created");
// This results in just one handler
$('#btn').on("click", function () {
alert("btn clicked handler");
});
// This results in a handler being attached every time the page is created
$(document).on("click", "#btn", function () {
alert("document clicked handler");
});
});