views:

56

answers:

2

This is probably pushing the limits of jquery.

I want to have the live() event triggered. But I only want to let it be triggered once using perhaps the one() event.

Currently I have the code blow. How do I restrict this to only being called once.

 $(".sub-content").live('click', function() {
  var id = this.id;
     $.get("InfoRetrieve", { theid:id }, function(data) { addContent(data, id) } );
 });
+1  A: 

There are a few ways of doing it. Firstly you can just use a marker:

<div class="sub-content not-loaded">...</div>

with:

$("div.sub-content.not-loaded").live("click", function() {
  $(this).removeClass("not-loaded");
  ...
});

Obviously you can do this the other way as well (add a class to mark that it's been loaded). I'm not 100% the above will be handled correctly with live() in which case:

$("div.sub-content.not-loaded").live("click", function() {
  if ($(this).hasClass("not-loaded")) {
    $(this).removeClass("not-loaded");
    ...
  }
});

will work.

Alternatively you can unbind the event.

$("div.sub-content").click(load_content);

function load_content() {
  $(this).unbind("click", load_content);
  ...
}

I'm not 100% sure that'll work with live() however (as live() may just rebind it).

cletus
It doesn't seem to work in this case, but I definitely learnt something anyway, thanks.
Ankur
A: 

You can use the die method:

$(".sub-content").live('click', function() {
   $(this).die('click');
   var id = this.id;
   $.get("InfoRetrieve", { theid:id }, function(data) { addContent(data, id) } );
});

I never tested it though.

Guillaume Flandre
That's going to remove all the click events. The OP only wants to make sure each div only loads once, which isn't quite the same thing. Your way would kill all click events when the first div was clicked so none others could be clicked.
cletus