search

Home  >  Q&A  >  body text

javascript - addEventListen passes this into the second parameter to implement binding events

Recently I was looking at the source code implementation of some libraries, and I discovered that this was passed into the second parameter of addEventListener. I felt confused, so I came up to ask questions. The following code is what I simply simplified and passed the test

    <script>
        this.onclick=function(){
            console.log('onclick');
        }
        app.addEventListener('click',this);
    </script>

Why can events be bound in this way?

怪我咯怪我咯2752 days ago939

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-05-18 11:05:11

    The

    addEventListener的第二个参数可以传一个对象,当事件触发时,这个对象的handleEvent method is called like this:

    document.body.addEventListener(
        'click',
        {
            handleEvent: function() {
                alert('body clicked');
            }
        },
        false);

    Reference:
    handleEvent of the second parameter of addEventListener
    http://peter.michaux.ca/artic...
    MDN

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-18 11:05:11

    Are you sure this addEventListener is the native JS window.addEventListener?

    reply
    0
  • Cancelreply