Samantha J T Star
Samantha J T Star

Reputation: 32808

How can I convert this javascript / jQuery into a "not inline" function?

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?

Upvotes: 2

Views: 420

Answers (2)

Adam Rackis
Adam Rackis

Reputation: 83366

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);

Upvotes: 4

BartekR
BartekR

Reputation: 3977

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/

Upvotes: 3

Related Questions