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

Commit

Permalink
fix: Prevent adding listener for xhrhttprequest multiple times
Browse files Browse the repository at this point in the history
* fix bug add event listener to xhrhttprequest multiple times and invalid request call (#529)
* fix bug add event listener to xhrhttprequest multiple times #527
* fix #287 with a better solution to prevent memory leak
* fix #530 for xhr request to an invalid url cause Schedule task count failed
  • Loading branch information
JiaLiPassion authored and mhevery committed Dec 18, 2016
1 parent 2594817 commit 9509747
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
17 changes: 14 additions & 3 deletions lib/browser/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ patchXHR(_global);

const XHR_TASK = zoneSymbol('xhrTask');
const XHR_SYNC = zoneSymbol('xhrSync');
const XHR_LISTENER = zoneSymbol('xhrListener');
const XHR_SCHEDULED = zoneSymbol('xhrScheduled');

interface XHROptions extends TaskData {
target: any;
Expand All @@ -62,19 +64,28 @@ function patchXHR(window: any) {
}

function scheduleTask(task: Task) {
self[XHR_SCHEDULED] = false;
var data = <XHROptions>task.data;
data.target.addEventListener('readystatechange', () => {
// remove existing event listener
var listener = data.target[XHR_LISTENER];
if (listener) {
data.target.removeEventListener('readystatechange', listener);
}
var newListener = data.target[XHR_LISTENER] = () => {
if (data.target.readyState === data.target.DONE) {
if (!data.aborted) {
if (!data.aborted && self[XHR_SCHEDULED]) {
task.invoke();
}
}
});
};
data.target.addEventListener('readystatechange', newListener);

var storedTask: Task = data.target[XHR_TASK];
if (!storedTask) {
data.target[XHR_TASK] = task;
}
sendNative.apply(data.target, data.args);
self[XHR_SCHEDULED] = true;
return task;
}

Expand Down
12 changes: 12 additions & 0 deletions test/browser/XMLHttpRequest.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,4 +182,16 @@ describe('XMLHttpRequest', function() {
expect(XMLHttpRequest.LOADING).toEqual(3);
expect(XMLHttpRequest.DONE).toEqual(4);
});

it('should work properly when send request multiple times on single xmlRequest instance', function() {
testZone.run(function() {
var req = new XMLHttpRequest();
req.open('get', '/', true);
req.send();
req.onloadend = function() {
req.open('get', '/', true);
req.send();
}
});
})
});

0 comments on commit 9509747

Please sign in to comment.