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元素監聽自定義事件
// 觸發自定義事件(dispatchEvent 除非事件的參數是必填項,切必須為事件對象)
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); } }