js 自定义事件、js 自定义事件处理

1.自定义事件:

js 一般事件像是click、blur、focus等等。除了这些之外还可以自己定义事件,但是自定义事件同样需要自己定义触发机制,此要注意,个人任务可以在某个view自带的事件处理机制中插入个人事件处理。

CustomEvent对象有2个参数

detail:配置项,默认值为null。

bubbles:冒泡标识

cancelable:是否可取消标识

示例:

let custom = new CustomEvent('test_event',{detail:{e_name : " this is a test "}})
// 某个dom元素监听自定义事件
let div = document.createElement("DIV");
div.addEventListener("test_event",function(e){console.log(e.detail.e_name)},false)
// 触发自定义事件(dispatchEvent 除非事件的参数是必填项,切必须为事件对象)
div.dispatchEvent(custom);// this is a test 

2.自定义事件处理

handleEvent 对象为事件处理的默认对象,我们可以重新定义它,先看一个click 事件对象

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

打印结果如下:

其中有一个属性为type = click ,也就是click 事件了。

 自定义事件处理:

let div = document.createElement("DIV")
// 通过handleEvent 处理监听到的事件
let custom_handle_event = { 
    handleEvent :function(e){
        console.log(e);
        if(e.type === 'click'){
            this.customClick(e);
        }
    },
    customClick : function(e){
          console.log("custom_click::",e);
    }
}
// 监听click事件并进行处理
div.addEventListener('click',custom_handle_event)
div.click()
// console 

打印结果如下

相比较单独处理事件,通过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); } }

猜你喜欢

转载自www.cnblogs.com/jony-it/p/11225254.html