Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Mobile delegate vs live vs bind

I can't seem to wrap my head around the differences between the following in jQuery Mobile:

$( document ).live('pageshow', function(event) {
});

$( document ).bind('pageshow', function(event) {
});

$( document ).delegate("#page", "pageshow", function() {
});

How do I execute scripts in the head of my documents that are DIFFERENT in certain pages? Which methods do I use to call those scripts?

Update: jQuery version: 1.7.1 jQuery Mobile version: 1.1.0

like image 228
cusejuice Avatar asked May 09 '12 16:05

cusejuice


People also ask

What is the difference between bind () live () and Delegate ()?

The bind() method will not attach events to those elements which are added after DOM is loaded while live() and delegate() methods attach events to the future elements also. The difference between live() and delegate() methods is live() function will not work in chaining.

How does jQuery live work?

jQuery live() Method The live() method attaches one or more event handlers for selected elements, and specifies a function to run when the events occur. Event handlers attached using the live() method will work for both current and FUTURE elements matching the selector (like a new element created by a script).


1 Answers

You would bind to a "page event" that jQuery Mobile exposes, like pageinit:

$(document).delegate('#my-page', 'pageinit', function () {
    //this is like document.ready for this pseudo-page
});

Since you're using jQuery Core 1.7.1 you can use .on() which has a slightly different syntax:

$(document).on('pageinit', '#my-page', function () {
    //this is like document.ready for this pseudo-page
});

All three of your methods do similar things. .live() is the same thing as using .delegate() with document as the root selection but it's been depreciated so it's a good idea to stop using it (source: http://api.jquery.com/on). Using .bind() directly on the document element is the same as using .delegate() but when you use .bind() you have to determine which pseudo-page had the event fired on it in the event handler rather than in the function call.

For example:

$(document).bind('pageshow', function () {
    var id = $.mobile.activePage[0].id;
    //you can use $.mobile.activePage to do work on the current page
});

In general, event delegation is used when we don't know when an element will exist in the DOM. It relies on events bubbling up the DOM until they get to the root selection (in your case it's always the document element).

Docs for .delegate(): http://api.jquery.com/delegate

For more general information about the difference between these functions, see this article (I've read it to check it for accuracy and it's right-on): http://www.elijahmanor.com/2012/02/differences-between-jquery-bind-vs-live.html

like image 146
Jasper Avatar answered Sep 29 '22 06:09

Jasper