Why use event listeners over function calls?

前端 未结 5 1725
盖世英雄少女心
盖世英雄少女心 2021-01-17 12:02

I\'ve been studying event listeners lately and I think I\'ve finally gotten them down. Basically, they are functions that are called on another object\'s method. My questi

5条回答
  •  死守一世寂寞
    2021-01-17 12:25

    My question is, why create an event listener when calling the function will work just fine?

    What if you don't know what function you want to call?

    Take the classic example, a Button that the user can click on. Whoever writes the library has no idea what function you want called when the button is clicked. It would also be pretty prohibitive if every Button could only call the same function when it is clicked.

    So instead, you can attach an event handler to the event. Then when the event is triggered, the Button can do what it needs to, without having to know at compile-time exactly what function it's supposed to be calling.

提交回复
热议问题