The introduction
We can bind events using dom0 and DOM2 event binding methods. The browser has a listening thread that executes the corresponding method and passes in the event object when the event is raised
Simulated event triggering
But if we don’t want to trigger the event manually, for example to trigger a click event we need to actually click, but we want to do the same thing in a logic with code directly, we can use it Elementobject.onclick () but we can not get the event object EV, can be done by the following way to simulate the trigger click event incompatible with IE6~8
const ev = document.createEvent("MouseEvent") // The arguments in DOM2 are plural and DOM3 is singular
// MouseEvent can also be KeyBoardEvent/Event, corresponding to initXxx below
ev.initMouseEvent("click".true.true) // Simulate event object data
// The second argument: whether to bubble
// Third parameter: whether the event can be cancelled
elementObj.dispatchEvent(ev)
// The click event that triggers this DOM object also passes the EV event object
Copy the code
Custom events
When it comes to custom events, the publish-subscribe model comes to mind
// Publish subscribe for singleton pattern
(function(){
//
const pond = {}
const on = function on(type,func){! pond[type]? pond[type]=[]:null
if(! pond[type].includes(func)){ pond[type].push(func) } }const off = function off(type,func){
if(pond[type]){
pond[type].forEach((item,index) = >{
if(item===func){
pond[type][index]=null})}}}const fire = function fire(type,... parmas){
let arr = pond[type]
if(arr){
let i=0
for(i; i<arr.length; i++){if(! arr[i]){ arr.splice(i,1)
i--
continue} arr[i](... parmas) } } }return {on,off,fire}
})()
Copy the code
This mimics the removal and firing of bindings for events, but it is still not possible to bind and pass in event objects via addEventListener, where you can customize events
elementObj.addEventListener("event_name",func)
const ev = document.createEvent("CustomEvent")
ev.initCustomEvent("event_name".true.true)
elementObj.dispatchEvent(ev)
Copy the code