Skip to content
Advertisement

How to return “addEventListener()” from another function – Javascript

I am trying to make my code shorter and more optimized, and want to make it look clearer.

So far I did this :

JavaScript

Now I have the possibility to call qs("#myElement"). Now I want to attach a event to the specified element just like qs("#myElement").addEventListener("click", callBack). It works great for me. But when I try to make this :

JavaScript

And then try to call qs("#init-scrap").ev("click", someFunction) then it pops up the following error :

Uncaught (in promise) TypeError: qs(...).ev is not a function.. I don’t know what is the problem, do I have to try method chaining ? or any other way I can resolve this problem.

Note : I don’t want to use any libraries or frameworks liek Jquery etc.

Advertisement

Answer

If you wish to use syntax qs("#init-scrap").ev("click", someFunction), you need to wrap object returned by querySelector into another object that has ev function.

JavaScript

It’s called Fluent interface, if you wish to look it up.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement