I have a jquery app with multiple data-roles=”page” in one html file.
Is it better to Bind all my buttons at first? Or bind the buttons that are on a certain “page” on pagecreate event?
Any benefits of doing one over the other?
ex:
<script>
$(document).delegate("#page1",'pagecreate', loadedFirstPage);
$(document).delegate("#page2",'pagecreate', loadedSecondPage);
function loadedFirstPage(){
$('#link1').bind('tap',function(){
console.log('Hello World');
});
//HERE?
$('#link2').bind('tap',function(){
console.log('Hello World Again');
});
}
function loadedSecondPage(){
//OR HERE?
$('#link2').bind('tap',function(){
console.log('Hello World Again');
});
}
</script>
<div id="page1" data-role="page">
<a href="#page2" id="link1">Click here</a>
</div>
<div id="page2" data-role="page">
<a href="#page1" id="link2">Click here Again</a>
</div>
The thing to take into consideration is that using
.bind()iterates over the whole list of elements selected and runs the binding function on each element. So if you have a ton of elements (hundreds or more) then you probably only want to bind to the ones on the current page. However if you are dealing with a few elements, say less than 100, then you don’t need to go through the extra step of delegating your event bindings.If you bind to all the elements at once then you can run the code inside the
document.readyevent handler or simply place the JS code at the end of the HTML document so all the elements on the page are available when the JS runs.