2013年3月18日 星期一

addeventlistener 的第三個參數


在Mozilla的網頁上 我們可以看到 addeventlistenter的定義是

Syntax

target.addEventListener(type, listener[, useCapture]);
type
A string representing the event type to listen for.
listener
The object that receives a notification when an event of the specified type occurs. This must be an object implementing theEventListener interface, or simply a JavaScript function.
useCapture Optional
If trueuseCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture. See DOM Level 3 Events for a detailed explanation. Note that this parameter is not optional in all browser versions. If not specified, useCapture is false.
但到底什麼是useCapture呢,其實就是說,我們新加的event,要在哪一個Phase下被呼叫

Event呼叫分成三個步驟
1.Capture phase
2.Target phase (Found target object)
3.Bubbling phase
如下圖
Event propagation flow diagram

當useCapture = false代表要在Bubbling phase才呼叫event,因此,新加的event會等他所有children的event handlers做完後,才會被呼叫。
反之,當useCapture = true代表要在Capture phase呼叫event,因此,新加的event會在他child event handler被呼叫前,先被呼叫。

沒有留言:

張貼留言