Skip to content
This repository has been archived by the owner on Apr 12, 2024. It is now read-only.

Commit

Permalink
test(browserTrigger): allow event bubbling
Browse files Browse the repository at this point in the history
In some browsers, events don't bubble when they are dispatched on node inside
a detached tree. When this is the case, the bubbling is made manually.
This may be convenient when unit testing directives, for example.
  • Loading branch information
Gonzalo Ruiz de Villa committed Sep 10, 2015
1 parent be609f8 commit d817bc1
Showing 1 changed file with 54 additions and 1 deletion.
55 changes: 54 additions & 1 deletion src/ngScenario/browserTrigger.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,12 @@
return originalPreventDefault.apply(evnt, arguments);
};

element.dispatchEvent(evnt);
if (!eventData.bubbles || supportsEventBubblingInDetachedTree() || isAttachedToDocument(element)) {
element.dispatchEvent(evnt);
} else {
triggerForPath(element, evnt);
}

finalProcessDefault = !(angular['ff-684208-preventDefault'] || !fakeProcessDefault);

delete angular['ff-684208-preventDefault'];
Expand Down Expand Up @@ -156,4 +161,52 @@

return evnt;
}

function supportsEventBubblingInDetachedTree() {
if ('_cached' in supportsEventBubblingInDetachedTree) {
return supportsEventBubblingInDetachedTree._cached;
}
supportsEventBubblingInDetachedTree._cached = false;
var doc = window.document;
if (doc) {
var parent = doc.createElement('div'),
child = parent.cloneNode();
parent.appendChild(child);
parent.addEventListener('e', function() {
supportsEventBubblingInDetachedTree._cached = true;
});
var evnt = document.createEvent('Events');
evnt.initEvent('e', true, true);
child.dispatchEvent(evnt);
}
return supportsEventBubblingInDetachedTree._cached;
}

function triggerForPath(element, evnt) {
var stop = false;

var _stopPropagation = evnt.stopPropagation;
evnt.stopPropagation = function() {
stop = true;
_stopPropagation.apply(event, arguments);
};
patchEventTargetForBubbling(evnt, element);
do {
element.dispatchEvent(evnt);
} while (!stop && (element = element.parentNode));
}

function patchEventTargetForBubbling(event, target) {
event._target = target;
Object.defineProperty(event, "target", {get: function() { return this._target;}});
}

function isAttachedToDocument(element) {
while (element = element.parentNode) {
if (element === window) {
return true;
}
}
return false;
}
}());

0 comments on commit d817bc1

Please sign in to comment.