js custom events, js custom event handlers

1. Custom events:

js general events such as click, blur, focus, and so on. In addition to these you can also define their own events, but also need their own custom events defined trigger mechanism, this should be noted, individual tasks can be inserted in the individual event handler that comes with a view event handling mechanism.

CustomEvent object has two parameters

detail: configuration item, the default value is null.

bubbles: Bubble logo

cancelable: whether to cancel the identity

 

Example:

Custom = the let new new CustomEvent ( 'test_event', {Detail: The e_name {: "the this IS A Test"}}) 
// dom element a custom event listener
the let div = document.createElement ( "the DIV");
div.addEventListener ( "test_event", function (E) {console.log (e.detail.e_name)}, false)
// trigger a custom event (dispatchEvent parameters unless the event is required, must be cut event object)
div.dispatchEvent (Custom); // the this IS A Test 

 

 

2. Custom Event Processing

The default object handleEvent object event handling, we can redefine it, look at a click event object

div.addEventListener('click',function(e){console.log(e)},false);
div.click();

Print results are as follows:

There is a property of type = click, that is, a click event.

 Custom event handlers:

div = document.createElement the let ( "the DIV" )
 // monitored by handling events handleEvent 
the let custom_handle_event = { 
    handleEvent: function (E) { 
        the console.log (E); 
        IF (e.type === 'the Click' ) {
             the this .customClick (E); 
        } 
    }, 
    CustomClick: function (E) { 
          the console.log ( "custom_click ::" , E); 
    } 
} 
// listen for the click event and processed 
div.addEventListener ( 'click' , custom_handle_event ) 
div.click () 
// Console

Print results are as follows

相比较单独处理事件,通过handleEvent 可以处理多个事件,例子比较多的像touch事件,例如(下面是个监听长按的例子):

let custom_handle_event = { 
    time : null,
    handleEvent :function(e){
        if(e.type === 'touchstart'){
            this.customStart(e);
                    
        }
        if(e.type === 'touchend'){
             this.customEnd(e);
        }
    },
  // 监听touchstart 与 touchend事件处理,设置长按阈值为2秒,如果touchend 小于2秒则清除time事件 customStart:
function(e){ this.time = setTimeout(function(){console.log("长按")},2000); }, customEnd : function(e){ clearTimeout(this.time); } }

 

Guess you like

Origin www.cnblogs.com/jony-it/p/11225254.html