Suppose there is a button, is it possible to hang an event on it and that from another place in the code other subscriptions to this event would not work? That is, only one first subscription worked. Or is it a crutch method?

example:

$("button").click(function(){ alert("one"); }); $("button").click(function(){ alert("two"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button> click me </button> 

it is necessary that there was only one message and worked once, that is, to remove the event after its execution

  • single time it means only one handler ? or just one trigger? Add an example of use code with a description of the behavior is not yet completely clear - Grundy
  • @Grundy one operation, now I will write the code. - perfect
  • and that from another place of the code other subscriptions to this event did not work - this part is especially incomprehensible :-) - Grundy
  • @Grundy added an example - perfect
  • This is only a bloody patch addEventListener possible. Out of the box is not supported. You can add a handler to any item at any time. - Grundy

1 answer 1

If only JS then something like this.

 var clickFunction = function (event) { window.removeEventListener('click',clickFunction, false ); }; window.addEventListener("click", clickFunction, false); 

If jQuery then use $ .one

  • there the question was updated (an example was added), your answer does only half of what you need - Grundy
  • And why don't you delete all the events to the element ($ .unbind ()) and then set your own. - Daniel Abyan September
  • for example, because you cannot control when someone else can add a handler to call unbind . Plus an unsolvable problem with the event delegation - Grundy
  • Well, I'm not the author of the question :-) - Grundy
  • :) Yeah. I know this decision. On the $('button') element $('button') you set the onMouseOver event. As the event works, you delete all the 'click' events leaving only yours. This will not solve the problem completely, but some solution will give. - Daniel Abyan September