Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I would like to delegate the event one for the click. Does anyone know if it is possible to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
161 views
Welcome To Ask or Share your Answers For Others

1 Answer

I'm going to assume that you want the event to fire only once PER matched element rather than unbind entirely on the first click.

I'd implement it like so:

$('#container').delegate('.children', 'click', function() {
  if($(this).data('clicked')) {
      return;
  }

  // ... your code here ...


  $(this).data('clicked', true);

});

This will fire only once per element. Technically, it fires everytime but is flagged the first time it is clicked so the code will not execute again.

The inherent problem of simulating a .one() handler w/ delegate is that using .one() each element that was matched in the selector is bound its own event handler. So when it is fired for the first time it unbinds/removes the handler from that element. You can't do that with .delegate() because only a SINGLE handler is being used for ALL the matched elements.

While the code above simulates it perfectly, it is still somewhat hackish because it doesn't literally do the same thing that .one() does (unbinding an event handler).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...