0

I have code:

$(Page).on('click', '*', function(e)
{
    myFunction();
}

function myFunction(){//do something...}

I would like the code in the function to be done only once, now when I click, for example, 5 times, the code from the function myFunction() will be executed 5 times. I don't want to change on('click', '*', ...

rollstuhlfahrer
  • 3,988
  • 9
  • 25
  • 38
Pat
  • 117
  • 1
  • 9
  • 2
    Use `one()` instead of `on()`. It behaves the same, but it unbinds after the first time it executes. – Taplar Apr 05 '18 at 16:49
  • 1
    Possible duplicate of [Simplest/Cleanest way to implement singleton in JavaScript?](https://stackoverflow.com/questions/1479319/simplest-cleanest-way-to-implement-singleton-in-javascript) – Nelson Teixeira Apr 05 '18 at 16:50
  • a global var? myfunctionRunned = false; and when is executed inside myFunction() just ask if(myfunctionRunned) – Roy Bogado Apr 05 '18 at 16:52

2 Answers2

1

Use jQuery's one method.

Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

Simply change your .on to .one.

$(Page).one('click', '*', function(e) {
  myFunction();
});

function myFunction() {
  // do something
}

Here's the documentation for one

rollstuhlfahrer
  • 3,988
  • 9
  • 25
  • 38
Philipp Meissner
  • 5,273
  • 5
  • 34
  • 59
0

You can use the function $.one

$(Page).one('click', '*', function(e)
     myFunction();
});

Or, better:

$(Page).one('click', '*', myFunction);

Be careful with that event delegation who will bind the event click to the whole set of elements within the DOM tree of Page.

Ele
  • 33,468
  • 7
  • 37
  • 75
  • 1
    Uh, it doesn't bind to all of them, it just matches against all the children. It's still just bound to whatever `Page` is. – Taplar Apr 05 '18 at 16:52