2

I hvae the following code:

$(".openDialog").live("click", function (e) {
    e.preventDefault();

    $("<div></div>")
    .addClass("dialog")
    .attr("id", $(this).attr("data-dialog-id"))
    .appendTo("body")
    .dialog({
        title: $(this).attr("data-dialog-title"),
        close: function () { $(this).remove() },
        modal: true
    })
    .load(this.href);
});
$(".close").live("click", function (e) {
    e.preventDefault();
    $(this).closest(".dialog").dialog("close");
});

Can someone explain how I can decouple the functions form the actions? I am a bit confused with how to do this.

Also what is the purpose of "live" ? I heard before someone suggesting "on". Is "on" better than "live" and how does it actually work?

2
  • All functions in JavaScript as just values. Take function callback () {};: now, in the applicable scope, callback merely evaluates to said function-object. Commented Jan 12, 2012 at 6:55
  • as far as second part of the question is concerned live is deprecated on is included in the version 1.7+ if you dont have the latest version of jQuery then try using delegate, the purpose is to attach the event handlers to the dynamically added elements to the DOM... Commented Jan 12, 2012 at 6:56

2 Answers 2

4

Just break the functions out, then pass the function name:

close: closeFunction    

function closeFunction() { 
   $(this).remove() 
}

$(".close").live("click", closeClick);

function closeClick(e) {
    e.preventDefault();
    $(this).closest(".dialog").dialog("close");
}

on is indeed better than live. Both allow you to wire up events to dynamically added content, but the former is more efficient, and the latter is deprecated, . Here's how you'd use it

$(document).on("click", ".close", closeClick);

or, ideally, if all these .close buttons were to be in a container, say, a div with id foo, you could more efficiently do

$("#foo").on("click", ".close", closeClick);

or for jQuery pre 1.7 you'd have to settle for delegate

$("#foo").delegate(".close", "click", closeClick);
Sign up to request clarification or add additional context in comments.

Comments

3

Also what is the purpose of "live" ? I heard before someone suggesting "on". Is "on" better than "live" and how does it actually work?

Since jQuery 1.7 .live is deprecated: http://api.jquery.com/live/

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

More about new .on() feature: http://blog.jquery.com/2011/11/03/jquery-1-7-released/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.