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.
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.
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/
Team Ravenglass
#1 by JJ on 4/2/12 - 6:54 PM
#2 by Dan G. Switzer, II on 4/2/12 - 7:44 PM
Not sure if the pageinit() method does anything to handle automatic unbinding of elements or not (my guess is jQuery mobile does something like $("*").off() for all elements in a fragment when it changes the page.)
Just keep that in mind, otherwise you'll have a bunch of dirty events attached.
#3 by Mike Goeppner on 4/2/12 - 9:48 PM
Its a poor choice for events that only belong on a single page or are only used once, but if you have an event that is used across the entire app in multiple elements, or if you have a plugin that creates many handlers this is a great choice. (Plus this technique can safely be used on the $(document).ready event with jQM unlike most event handlers which need to be used with pageInit() )
Like most things, it comes down to choosing the right techniques for the job.
#4 by MikeZ83 on 4/3/12 - 12:55 AM
#5 by Shelly Saxton on 5/3/12 - 8:48 AM