Use of javascript custom events | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Use of javascript custom events

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events I have read above linked article/documentation and still can't understand custom events. Events fired by browser (input , change , click , load etc) seems to be very useful. We can schedule our functions to get called on specific browser event. (for eg. sending data when button clicked) But in case of custom events we need to use dispatchEvent method of target object. Consider you create an animation in which an element is being translated from one position to another and you want to call a function when it reaches certain position in page. So here certain position could be a condition for calling a function. But custom events don't have any way to specify condition when function is called. we need to use dispatchEvent(). So...Why do we even need such events? Won't it be better if we just call the function instead of dispatching event ?

28th Jan 2020, 11:36 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
2 Answers
+ 4
Dispatching an event would asynchronously run a triggered event function, the execution of the animation time is less affected. Whereas calling a function is a synchronized execution, it might affect the execution of animation, if it take longer period to complete the function.
28th Jan 2020, 2:16 PM
Calviղ
Calviղ - avatar
+ 3
Simple conditional statement is preferred when the code is a small snippet, like what we used to do. Custom event is used when developing the condition and the consequences are separated. The programmers can develop the conditions part and the consequences part in different code base.
28th Jan 2020, 10:59 PM
Gordon
Gordon - avatar