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.

view plain print about
1<div data-role="page" id="demopage">
2
3 <div data-role="header">
4 <a data-rel="back" data-icon="home">Home</a>
5 <h1>.on() Demo Page</h1>
6 </div>
7
8 <div data-role="content">
9 <button class="testButton" data-bacon="I accidently ate all the bacon!">Test 1</button>
10 <button class="testButton" data-bacon="I like bacon!">Test 2</button>
11 <button class="testButton" data-bacon="That was my bacon!">Test 3</button>
12 <div id="status"></div>
13 </div>
14
15 <div data-role="footer">
16 <h4>Footer content</h4>
17 </div>
18
19</div>

Now let's bind a click event to the buttons so they display the value of the data-bacon attribute in the status div.

view plain print about
1$(document).on('click', 'button', function()
2 {
3 $("#status").text($(this).attr("data-bacon"))
4 });

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/

Reference: http://www.raymondcamden.com/index.cfm/2012/4/1/Reminder--Use-the-proper-jQuery-Mobile-event-handler http://api.jquery.com/on/