search

Home  >  Q&A  >  body text

javascript - How to implement jquery's on() method in native js.

How does native js implement jquery's on() method and support binding multiple events to an element at the same time?

For example:

element.on('click mouseout',function(){...});

How to achieve this using native JS?

我想大声告诉你我想大声告诉你2792 days ago1279

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-07-05 10:58:31

    Give you a simple example. If you want to use the on method in native JS, you can write it like this:

    HTMLElement.prototype.on = function(events, callback){
        let evs = events.split(' ');
        for(let event of evs){
            this.addEventListener(event, callback);
        }
        // 如果你想像JQuery一样支持链式调用,可以在这里返回this
        // return this;
    }

    There are many loopholes in this way of writing, because many situations are not considered. For example, IE's event binding is not considered. For example, multiple events do not consider multiple callbacks.

    But. After all, the purpose is to tell you your thoughts, not to reinvent the wheel for you.

    The implementation of JQuery probably follows the same logic. You can use this method to encapsulate your own library.

    reply
    0
  • typecho

    typecho2017-07-05 10:58:31

    addEventListener

    reply
    0
  • Cancelreply