Bug 163083

Summary: Overwriting an attribute event listener can lead to wrong event listener firing order
Product: WebKit Reporter: Chris Dumez <cdumez>
Component: DOMAssignee: Chris Dumez <cdumez>
Status: RESOLVED FIXED    
Severity: Normal CC: cdumez, commit-queue, darin, dbates, esprehn+autocc, kangil.han, rniwa, sam
Priority: P2 Keywords: WebExposed
Version: WebKit Nightly Build   
Hardware: Unspecified   
OS: Unspecified   
Attachments:
Description Flags
Patch
none
Patch none

Description Chris Dumez 2016-10-06 14:12:53 PDT
Overwriting an attribute event listener can lead to wrong event listener firing order. This is because we remove the old event listener and then append the new one in this case instead of actually replacing the new one.

e.g.
element.onclick = function() { console.log('NOT RUN'); }
element.addEventListener('click', function() { console.log('SECOND'); });
element.onclick = function() { console.log('FIRST'); }

Prints FIRST then SECOND on Gecko, but prints SECOND then FIRST on WebKit.
Comment 1 Chris Dumez 2016-10-06 14:17:05 PDT
Created attachment 290865 [details]
Patch
Comment 2 Darin Adler 2016-10-06 16:04:44 PDT
Comment on attachment 290865 [details]
Patch

View in context: https://bugs.webkit.org/attachment.cgi?id=290865&action=review

> Source/WebCore/dom/EventListenerMap.cpp:120
> +    listeners->at(index)->markAsRemoved();
> +    listeners->at(index) = RegisteredEventListener::create(WTFMove(newListener), options);

Should we use a reference to avoid calling at() twice?

> Source/WebCore/dom/EventListenerMap.h:58
> +    void replace(const AtomicString& eventType, EventListener& oldListener, Ref<EventListener>&& newListener, const RegisteredEventListener::Options&);

This interface is intrinsically inefficient. Callers always have to call find before you call replace, so will always have to search the map twice!

In the future for better efficiency we should consider adding an operation that does exactly the right thing so that setAttributeEventListener can be efficient. This would be analogous to HashMap::add function that either adds if there is no existing item, or returns the location of the existing item if there is one.
Comment 3 Chris Dumez 2016-10-06 16:44:54 PDT
Created attachment 290871 [details]
Patch
Comment 4 WebKit Commit Bot 2016-10-06 17:19:07 PDT
Comment on attachment 290871 [details]
Patch

Clearing flags on attachment: 290871

Committed r206889: <http://trac.webkit.org/changeset/206889>
Comment 5 WebKit Commit Bot 2016-10-06 17:19:12 PDT
All reviewed patches have been landed.  Closing bug.