fastclick源碼中涉及到自創(chuàng)建自定義事件,相關(guān)基礎(chǔ)知識(shí)要準(zhǔn)備:
首先,最簡(jiǎn)單的:** 創(chuàng)建一個(gè)事件并觸發(fā):**
// 第一種方法,但是已經(jīng)不推薦了,不過(guò)fastclick上用的這種
// Create the event.
var event = document.createEvent('Event');
// Define that the event name is 'build'.
event.initEvent('build', true, true);
// Listen for the event.
elem.addEventListener('build', function (e) {
// e.target matches elem
}, false);
// target can be any Element or other EventTarget.
elem.dispatchEvent(event);
//第二種,直接用構(gòu)造函數(shù)
var event = new Event('build');
// Listen for the event.
elem.addEventListener('build', function (e) { ... }, false);
// Dispatch the event.
elem.dispatchEvent(event);
相關(guān)連接見(jiàn):
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
fastclick中的真實(shí)做法
fastclick中有一個(gè)sendclick原型方法,目的是將模擬觸發(fā)targetElement的click事件。
touch = event.changedTouches[0];
// Synthesise a click event, with an extra attribute so it can be tracked
clickEvent = document.createEvent('MouseEvents');
/*2*/ clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
/*3*/ clickEvent.forwardedTouchEvent = true;
targetElement.dispatchEvent(clickEvent);
第三行的forwardedTouchEvent是給這個(gè)事件加的標(biāo)簽,方便跟蹤。
第二行的方法參數(shù)太多,完全可以寫(xiě)成更加易讀的形式:
clickEvent.initMouseEvent(this.determineEventType(targetElement), //type
true, //canBubble
true, //canCanceled
window, //view
1, //detail: 點(diǎn)擊了幾次
touch.screenX, //screenX
touch.screenY, //screenY
touch.clientX,
touch.clientY,
false, //ctrlKey,
false, //altKey
false, //shiftKey
false, //metaKey
0, //mouseEvent.button 0:鼠標(biāo)左鍵 1:鼠標(biāo)中鍵 2:鼠標(biāo)右鍵
null //相關(guān)節(jié)點(diǎn),在鼠標(biāo)點(diǎn)擊事件中設(shè)為null就好了,在mousein等事件中有用
);
相關(guān)連接:
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/initMouseEvent