DOM event listener and trigger

EventTargetAPI defines the DOM event (mouse event, etc.) listener and trigger method, all the DOM nodes deployed this interface.

This interface has three methods: addEventListener, removeEventListener, dispatchEvent.

一. EventTargetAPI

1. EventTarget.addEventListener(type, listener, options)

DOM Node object to add an event listener.

grammar:

eleTarget.addEventListener (type, listener [, with useCapture])
 // type: the DOM event type, case sensitive 
// listener: listening callback function, function (e) {}; e Event object is generated event occurs; 
// userCapture : Boolean value, whether to trigger the capture phase; corresponds {capture: boolean}

The second parameter is a callback function, the parameters are Event object inside the this, DOM node object point eleTarget.

  <button id="btn">ClickMe</button>
  <script>
    btn.addEventListener('click',function(e) {
      console.log(this === btn); // true
    })
  </script>

The third parameter may also be a configuration object:

eleTarget.addEventListener (of the type, listener, Options)
 // Options properties as follows: 
Options = { 
   Capture: boolean , // whether to trigger the capture phase; default false 
   Once: boolean , // whether to listen only once and then automatically removed; defaults to false, 
   passive: Boolean , // prohibit prentDefault () method; defaults to false 
}

To add a listening event with the same goal, the same as if the callback function is executed only once, and the rest ignored.

function hello() {
  console.log('Hello world');
}

document.addEventListener('click', hello, false);
document.addEventListener('click', hello, false); //自动忽略
// 运行结果
hello world

To add a listening event with the same goal, the callback function if different, then in accordance with the order of addition, in order to perform.

function hello() {
  console.log('Hello');
}
function world() {
  console.log('world')
}
document.addEventListener('click', hello, false);
document.addEventListener('click', world, false); 
// 运行结果
hello
world

Different on [event] and DOM object of this event, on [Event] will cover only the last act;

And only in the bubbling stage trigger , you can not specify the stage trigger.

function hello() {
  console.log('Hello');
}
function world() {
  console.log('world')
}
document.onclick = hello;
document.onclick = world;
// 运行结果
world

In addition, HTML is on [event] event, within the quotation marks is executable JS code

<div onclick="hello()">ClickMe</div>

2. EventTarget.removeEventListener(type, listener, options)

grammar:

function Hello () { 
   the console.log ( "Hello" ); 
} 
element.addEventListener ( 'the Click', Hello, to true ); 
element.removeEventListener ( 'the Click', Hello, to true );
 // Note 
// Remove method of action element and the following parameters must be exactly the same. 
// and the second argument must be variable as a function of transfer; otherwise, the equivalent of a new function, even if the content and add in, just as a new function

3. EventTarget.dispatch(event)

Manual trigger monitor function, triggered by the code;

Parameters can not be empty, must be the Event object;

It returns a Boolean value that indicates whether to trigger success; returns the value returned after listening function execution is complete.

Example:

  btn.addEventListener('click',function(event) {
    console.log('listener end')
  })
  console.log(btn.dispatchEvent(new Event('click')));
 // 运行结果如下:
 listener end
 true

application: 

You can customize an event listener function, the function call is triggered in the desired position.

  btn.addEventListener('lyra',function(event) {
    console.log('Be dispatched at i=2')
  })
  btn.addEventListener('myevent',function(event) {
    console.log('Be dispatched at i=1')
  })
  for(let i=0; i < 10; i++) {
    if (i === 1) {
      btn.dispatchEvent(new Event('myevent'));
    }
    if (i === 2) {
      btn.dispatchEvent(new Event('lyra'));
    }
  }
  // 运行结果
  Be dispatched at i=1 //i===1时先触发myevent
  Be dispatched at i=2

Two. Event event

Monitor and trigger the basis of the above function is the Event object.

Event is js native objects, each object DOM events generated are instances of it.

It is a constructor, an instance of an event can be customized.

The syntax is as follows:

Event = const new new Event (of the type, Options);
 // of the type is the type of custom events 
// Options are custom event configuration

There are two options attributes:

Options = const { 
  bubbles: boolean , // specify whether the event can bubble; default false, triggered only during the capture phase 
  cancelable: boolean , // Specify whether the event can call the preventDefault () method 
}

Three. CustomEvent event

Event events and constructors difference is: can pass custom data attributes triggered by detail.

const data = fetch(url);
const event = new CustomEvent('myevent', {
   bubbles: false,
   cancelable: false,
   detail: data
})
ele.addEventListener('myevent', function(e){
   console.log(e.detail); //data
})
ele.dispatch(event)

IV. Applications

DOM nodes simultaneously bind click event and double-click event

let previous=0;
let timer;
btn.addEventListener('click', function(e) {
  const diff = e.timeStamp - previous;
  if (diff < 300) {// 双击
    console.log('double click');
    clearTimeout(timer);
  } else {
    timer = setTimeout(function() {
      console.log('single click')
    },300);
    previous = e.timeStamp;    
  }
},false);

 

Guess you like

Origin www.cnblogs.com/lyraLee/p/11840466.html