Start a new topic

Proper Anonymous Click Event Usage

What is the PROPER way to use onclick and clean up anonymous delegates.


I have this code:

el.onclick += (MouseEvent e1) => {

 (...) 

 return false;
 };

 

Should i be using += to Attach another anonymous click event?

 

Should i just use = to assign my new anonymous click event?

 

Is it necessary to remove anonymous event click event and HOW?


Should i even be using anonymous click event like SHOWN ABOVE?


1 Comment

Q: Should i be using += to Attach another anonymous click event?

A: += will add it to event chain (not recommended with anonymous handler, can't be removed),

    = will override and reassign only one handler.

 

Q: Should i just use = to assign my new anonymous click event?

A: Again for anonymous handler it's the only correct way, remove it later by onclick = null;

 

Q: Is it necessary to remove anonymous event click event and HOW?

A: Highly recommended, the only way remove it is using onclick = null;


Q: Should i even be using anonymous click event like SHOWN ABOVE?

A: In good practice NOT, store the anonymous event handler in some variable, and use this variable to remove it later.


Actually all your questions are good in pure C# practice as well and have the same answers.


And one more thing in JS/DuoCode you can also use:
el.addEventListener('click', some_handler) and el.removeEventListener('click', some_handler)

Login or Signup to post a comment