Múltiples event listeners en JavaScript

22/Ago/2016 38

En JavaScript, para agregar un evento a un selector ó un conjunto de ellos se utiliza comúnmente addEventListener() pero que tiene una sutil limitación: sólo puedes darle 1 evento a la vez.

¿Por qué querría agregar más de un evento a un elemento?

Suena a locura pero puede suceder, principalmente en selectores HTML para formularios. La última vez que lo necesité fue para un elemento input de tipo number el cual agrega flechas para cambiar el valor, por lo que puedes ingresar un número por el teclado ó utilizando las flechas. Con eso, necesité escuchar el evento keyup y change para poder hacer algo con ese valor posteriormente:

JS Bin on jsbin.com

/**
 * multipleEventsListeners.js
 * Add the capability to attach multiple events to an element, just like jQuery does
 * https://gist.github.com/juanbrujo/a1f77db1e6f7cb17b42b
 */
 
function multipleEventsListeners(elem, events, func) {
  var event = events.split(' ');
  for (var i = 0; i < event.length; i++) {
    elem.addEventListener(event[i], func, false);
  }
}

/*
Use: 
var input = document.querySelector('input');
multipleEventsListeners(input, 'keyup change', function(e){
  console.log(this.value);
});
*/

ES6:

function multipleEventsListeners(elem, events, func) {
  events.split().forEach(e => elem.addEventListener(e, func, false));
}

/*
Use: 
const input = document.querySelector('input');
multipleEventsListeners(input, 'keyup change', function(e) {
  console.log(this.value);
});
*/

Link:

Comentarios

  1. Reina [#]

    justo lo que buscaba :/

  2. Fabrico [#]

    Hola, su ejemplo es justo lo que estaba buscando, pero al implementarlo no me sale nada en la consola.
    ¿Usted probo si el ejemplo funcionaba?

  3. bluray [#]

    I loved as much as you will receive carried out right here. The sketch is attractive, your authored subject matter stylish. nonetheless, you command get got an nervousness over that you wish be delivering the following. unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you shield this hike.| Natalina Vaclav Idalia

  4. 720p [#]

    Thanks for sharing, I can relate to an certain extent. Cristine Marvin Ginsberg

  5. diziler [#]

    Nice read, I just passed this onto a colleague who was doing a little research on that. And he just bought me lunch since I found it for him smile Thus let me rephrase that: Thank you for lunch! Korie Yvor Tarrah

  6. dublaj [#]

    Absolutely indited content , appreciate it for selective information . Shanta Winslow Salesin

  7. dizi [#]

    There is apparently a lot to realize about this. I think you made some nice points in features also. Ardine Mischa Lesya

  8. fringe [#]

    Way cool! Some extremely valid points! I appreciate you writing this article and also the rest of the site is really good.| Sheela Maxie Gotthelf

  9. 720p [#]

    I was more than happy to uncover this page. I wanted to thank you for ones time for this particularly wonderful read!! I definitely really liked every little bit of it and I have you saved to fav to check out new information in your site. Daisey Patric Trinette

  10. bluray [#]

    I blog quite often and I genuinely appreciate your information. Your article has really peaked my interest. I will book mark your blog and keep checking for new information about once a week. I opted in for your RSS feed as well. Tammi Connie Andi

  11. bedava [#]

    After research a few of the blog posts on your website now, and I truly like your approach of blogging. I bookmarked it to my bookmark web site list and will probably be checking back soon. Pls take a look at my web page as nicely and let me know what you think. Henka Wendall Martinson

  12. hindi movie [#]

    I enjoy what you guys are usually up too. This kind of clever work and reporting! Marlane Ian Vetter

  13. bedava [#]

    I like to party, not look articles up online. You made it happen. Latashia Maury Gayl

  14. erotik [#]

    If some one needs to be updated with most recent technologies then he must be visit this web page and be up to date every day.| Anette Gilburt Buskirk

  15. 720p [#]

    the time to read or visit the content material or web pages we have linked to below the Fannie Tirrell Forward

  16. turkce [#]

    the most common electrical supply that i always buy at the local store is the elecrtical tape and electrical wire` Lizbeth Harcourt Eula

  17. dizi [#]

    Evelyn Hugo is one of my favorites as well. So amazing. Lelia Aldus Jeana

  18. turkce [#]

    I really appreciate free, succinct, reliable data like this. Ester Weider Tansy

  19. turkce [#]

    Exactly, they talk a lot about Trader but you still can not buy the currency. Emalee Edd Claretta

  20. erotik [#]

    Hello there. I discovered your website by way of Google whilst looking for a similar topic, your web site got here up. It appears good. I have bookmarked it in my google bookmarks to visit then. Laryssa Oran Samal

  21. erotik [#]

    Wow! At last I got a website from where I know how to truly obtain valuable information concerning my study and knowledge. Sharia Gavin Loveridge

  22. cialis cialis [#]

    generic cialis canada

  23. güvenilir bahis siteleri [#]

    2021 yılına gelindiğinde dünyanın dört bir yanından katılımcı sağlayan canlı bahis şirketleri, aynı
    zamanda kullanıcılarına
    gerekli bilgileri paylaşmaya devam etmektedir.Sürekli kapanan güvenilir bahis siteleri sık sık domain güncellemektedir.

    Yeni domainlere ulaşmak, en güvenilir bahis sitelerinin en güncel girişlerini kaçırmamak ve marsbahis giriş
    adreslerini takip etmek için hangibet.com u ziyaret edebilirsiniz.

    HangiBET ziyaretçilerine ve oyunculara en güvenilir bahis sitelerinin resmi giriş adreslerini sunan,
    türkiyede çok popüler olan marsbahis giriş adresini güncel tutan güvenilir bir sitedir.

    Marsbahis giriş haftada 1-2 defa kapanmaktadır.En güncel marsbahis
    giriş adresini hangibet üzerinden takip edebilirsiniz.Piyasada çok fazla fake/dolandırıcı
    site bulunmakta bu sitelerden zarar görmemek için
    Hangibet üzerinden en güvenilir bahis sitelerine ulaşabilir güvenli bir şekilde oyununuzu oynayabilirsiniz.

    Güvenilir bahis siteleri size daima kaliteli, yüksek bonuslu,
    7-24 müşteri hizmetleri, canlı destek gibi özellikler
    sunar.
    Bu yüzden güvenilir bahis siteleri haricindeki
    sitelerde oynamanız önerilmez aksi takdirde mağdur olabilirsiniz.

    Mağdur olmamak adına hangibet üzerinden güvenilir
    bahis sitelerini tercih etmenizi öneririz.

  24. https://www.facebook.com/pages/category/Health---Wellness-Website/Vital-flow-reviews-102135748499657/ [#]

    This video is presenting does vital flow work but
    also try to cover the following subject:https://www.facebook.com/pages/category/Health—Wellness-Website/Vital-flow-reviews-102135748499657/

    -vital flow for prostate

    -vitalflow prostate really works

    -vitalflow prostate support reviews

    One thing I noticed when I was researching info on does vital flow
    work was the absence of appropriate details.

    Does vital flow work nevertheless is an subject that I know something about.
    This video therefore should be relevant and of interest to you.

    ~~~~~~~~~~~~~~~~~~~~~

    Follow our video clips about does vital flow work
    as well as other comparable topics on

    Hi there Dear, are you actually visiting this website daily,
    if so then you will absolutely obtain good experience.

  25. binance komisyon oranları [#]

    Binance komisyon oranları merak edenler için binance komisyon oranları!
    Tıklayın ve binance komisyon oranları sayfamıza göz atın. Binance
    komisyon oranları inceleyin!

  26. CBD oil for dogs [#]

    Just want to say your article is as astonishing. The clarity in your post is simply great and i can assume you’re an expert on this subject.
    Fine with your permission let me to grab your RSS feed to keep updated with forthcoming post.
    Thanks a million and please carry on the gratifying work.

    Here is my page CBD oil for dogs

  27. CBD for dogs [#]

    Hi there to all, how is everything, I think every one is getting more from this site,
    and your views are fastidious in support of new viewers.

    Feel free to surf to my page: CBD for dogs

  28. CBD for sale [#]

    Hello, I enjoy reading through your article. I like to
    write a little comment to support you.

    My page … CBD for sale

  29. cbd oil for sleep [#]

    of course like your web-site but you need to check the spelling
    on several of your posts. A number of them are rife with spelling
    problems and I in finding it very troublesome to inform the truth on the other hand I’ll
    surely come again again.

    Feel free to visit my web site :: cbd oil for sleep

  30. btcturk komisyon oranları [#]

    Btcturk komisyon oranları için tıklayın. Sizler için komisyon oranları sayfamızda komisyon oranları paylaştık.
    İşte Btcturk komisyon oranları!

  31. clubhouse davetiye [#]

    Clubhouse davetiye arıyorsanız clubhouse davetiye hakkında bilgi almak için hemen tıklayın ve clubhouse davetiye hakkında bilgi alın. Clubhouse davetiye sizler için şu
    anda sayfamızda yer alıyor. Tıkla ve clubhouse davetiye satın al!

  32. best cbd gummies for pain [#]

    Aw, this was an exceptionally good post. Finding
    the time and actual effort to generate a very good article… but what can I say… I hesitate a whole lot and never seem to get anything done.

  33. best cbd oil for dogs [#]

    wonderful post, very informative. I wonder why the opposite
    experts of this sector don’t notice this. You must continue your writing.
    I’m sure, you have a great readers’ base already!

  34. write my papers [#]

    Undeniably believe that which you stated.
    Youur favorite reaeon seemed to bbe on the internet the simplest tbing to be aare of.
    I say to you, I definitely gett irked while peoople consider worries
    that they plainly do not know about. You managed tto hit the
    nail upon the top as well as defined out the whole thing without having
    side-effects , people could take a signal. Will likely be back
    too get more. Thanks
    https://spark.adobe.com/page/kiaZgtXfO0qwG/
    wriote my papers
    write my papers https://against-schoo1244.hpage.com/buy-term-papers-online-from-experienced-writers.html

  35. 카지노사이트 [#]

    To see a world in a grain of sand. And a heaven in a wild flower

  36. 바카라사이트 [#]

    I added a new blog post yesterday. There’s a smaller list than usual in it.

  37. CBD gummies for sale [#]

    Greetings from Los angeles! I’m bored at work
    so I decided to check out your website on my iphone
    during lunch break. I enjoy the knowledge you provide here and can’t wait to take a look when I get home.
    I’m amazed at how quick your blog loaded on my phone ..
    I’m not even using WIFI, just 3G .. Anyways, good blog!

    Feel free to surf to my web blog – CBD gummies for sale

Responder a Jorge Epuñan ×

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

CSSLab