Isaac and I got into a discussion today stemming from an interesting blog post from Raymond Camden. Raymond was discussing how he had run into issues binding events in jQuery mobile on the 'pageshow' event. While the solution he presents is adequate, there is another neat way to do this.
.on() is a very powerful function that combines the functionality of three recently deprecated methods: .bind(), .live(), and .delegate()
Below is a tutorial on how to bind delegated events.
Let's take a basic jQuery mobile snippet with 3 buttons.
<a data-rel="back" data-icon="home">Home</a>
<h1>.on() Demo Page</h1>
<button class="testButton" data-bacon="I accidently ate all the bacon!">Test 1</button>
<button class="testButton" data-bacon="I like bacon!">Test 2</button>
<button class="testButton" data-bacon="That was my bacon!">Test 3</button>
Now let's bind a click event to the buttons so they display the value of the data-bacon attribute in the status div.
$(document).on('click', 'button', function()
So what happens here?
We call .on() passing 'click' as the event type, 'button' as the selector to apply the event to, and a function to run when the event fires.
Now, when you click a button on the body, #status displays the particular data-bacon attribute of the clicked button.
You can view the complete sample here: http://jsfiddle.net/Bw9Kh/