0

I have an HTMLCollection: document.getElementsByClassName('done') and now i want to implement a function addEventListeners.Now i can do it like this:

Object.prototype.addEventListeners = function(argument){
        Object.values(this).forEach(function(element, index) {
        });
    };

But i have read in numerous websites that extending native objects is a bad idea.So what are the alternatives?

RobG
  • 142,382
  • 31
  • 172
  • 209
askoasksao
  • 87
  • 1
  • 7
  • why don't use a framework like JQuery or AngularJS ? – FarukT Jan 30 '18 at 08:25
  • @FarukT i'm doing this for a better understanding of JS – askoasksao Jan 30 '18 at 08:25
  • 1
    As an alternate, you can attach a delegate to parent, if they have same parent or you can loop over on elements. You can use `Array.from(elementList, (el)=> { el.addEventListener(evenName, handler)})` – Rajesh Jan 30 '18 at 08:32
  • @str i'm not asking why it's bad,i'm asking for alternatives – askoasksao Jan 30 '18 at 08:35
  • @Rajesh but how can i turn into a handler – askoasksao Jan 30 '18 at 08:36
  • @askoasksao Just create your own class or functions which you pass arguments to (e.g. a selector and events). But that is also briefly mentioned in the duplicate question. – str Jan 30 '18 at 08:39
  • Handler is something that will handle an event. I guess you mean a utility function like `addEventListener`. There are few ways for this: 1. Add it to prototype(*Like in your code*). 2. Bleed it to global scope(`window.addEventListeners = ...`). 3. Create a utility can add it to this. This way, irrespective to domain/project, you will have your function(*Like jQuery, $().on(...)*). Personally, I prefer 3rd option. Issue with first 2 approach is, they are available on global scope, so anyone can change it and break your site. – Rajesh Jan 30 '18 at 08:40
  • @Rajesh thanks,utility is what i was looking for – askoasksao Jan 30 '18 at 08:43
  • 1
    If you extend natives, you should use `HTMLCollection` in this case – Jonas Wilms Jan 30 '18 at 08:46
  • @JonasW.—HTMLCollection is a host object, not a native object. ;-) Extending host objects is worse than extending native objects, since host objects are not as controlled. – RobG Jan 30 '18 at 09:00

0 Answers0