Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: events handling #121

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 26 additions & 4 deletions src/xhr-proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function trim(str) {
}

function getEventTarget(xhr) {
return xhr.watcher || (xhr.watcher = document.createElement('a'));
return xhr.watcher || (xhr.watcher = typeof document.createDocumentFragment === 'function' ? document.createDocumentFragment() : document.createElement('a'));
}

function triggerListener(xhr, name) {
Expand Down Expand Up @@ -157,6 +157,9 @@ function proxyAjax(proxy, win) {
return true;
}

var eventListenerFnMap = typeof WeakMap === 'function' ? function (_this) {
return _this.eventListenerFnMap || (_this.eventListenerFnMap = new WeakMap());
} : null;

var { originXhr, unHook } = hook({
onload: preventXhrProxyCallback,
Expand Down Expand Up @@ -210,18 +213,37 @@ function proxyAjax(proxy, win) {
if (onRequest) return true;
},
addEventListener: function (args, xhr) {
// args = (type:string , listener: EventListener, opt: any?)
var _this = this;
if (events.indexOf(args[0]) !== -1) {
var handler = args[1];
getEventTarget(xhr).addEventListener(args[0], function (e) {
var Gn = function (e) {
var event = configEvent(e, _this);
event.type = args[0];
event.isTrusted = true;
handler.call(_this, event);
});
};
if (eventListenerFnMap) {
var map = eventListenerFnMap(_this);
map.set(handler, Gn);
}
getEventTarget(xhr).addEventListener(args[0], Gn, false);
return true;
}
},
removeEventListener: function (args, xhr) {
// args = (type:string , listener: EventListener, opt: any?)
if (events.indexOf(args[0]) !== -1) {
var handler = args[1];
if (eventListenerFnMap) {
var map = eventListenerFnMap(this);
var Gn = map.get(handler);
if (Gn) {
getEventTarget(xhr).removeEventListener(args[0], Gn, false);
return true;
}
}
}
},
getAllResponseHeaders: function (_, xhr) {
var headers = xhr.resHeader
if (headers) {
Expand Down