tags:

views:

43

answers:

2

I have the following code

$(".reply").toggle
(
    function ()
    {
        x1();
    },
    function ()
    {
        x2();
    }
);

I need to use live, so new elements would also be bound. Is there some syntax to do it? Or will I need to implement a toggle on the click event?

I am using jQuery 1.4.2.

+1  A: 

live supports custom events in jquery 1.4. You could try something like this:

$(function () {
    $(".reply").live("customToggle", function () {
        $(this).toggle(
            function () {
                x1();
            },
            function () {
                x2();
            }
        );
    });

    $(".reply").live('click', function () {
        $(this).trigger('customToggle');
    });
});

this appears to work fine without a custom event:

$(".reply").live('click', function () {
    $(this).toggle(
            function () {
                x1();
            },
            function () {
                x2();
            }
        );
    $(this).trigger('click');
});
fehays
+1 nice way to do it :)
Sarfraz
Does not seem like a nice way to me. You're attaching event handlers each time you click on it?
Chetan Sastry
Yeah that didn't seem so good to me either. +1 for your answer. I like it better. I think a simple live click and your own toggle is "correct" way to do it.
fehays
+2  A: 

Just modified fehay's answer so that it does not rely on jQuery not attaching duplicate event handlers during toggle()

$(".reply").live('click', function () {
    var toggled = $(this).data('toggled');
    $(this).data('toggled', !toggled);
    if (!toggled) {
        x1();
    }
    else {
        x2();
    }
});

Besides, just keep in mind that the selectors for live have to be as specific as possible because of the way event delegation works. Every time something gets clicked on the document, jQuery has to climb up the tree checking if the element matches the selector.For the same reason, .delegate() is much more performant because you can limit the capture area.

Chetan Sastry
I will take it as a NO.
BrunoLM