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 :

function id(a) {
  return document.getElementById(a);
}

function cl(a) {
  return document.getElementsByClassName(a);
}

function tg(a) {
  return document.getElementsByTagName(a);
}

function qs(a) {
  return document.querySelector(a);
}

function qa(a) {
  return document.querySelectorAll(a);
}

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 :

function ev(e, call) {
  return addEventListener(e, callback);
}

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.

class jQueryLite {
  constructor(el) {
    this.el = el;
  }

  ev(e, callback) {
    this.el.addEventListener(e, callback);
    return this;
  }
}

qs(a) {
  return new jQueryLite(document.querySelector(a));
}

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