Skip to content

Commit

Permalink
fix bug add event listener to xhrhttprequest multiple times angular#527
Browse files Browse the repository at this point in the history
  • Loading branch information
JiaLiPassion committed Dec 6, 2016
1 parent a65881c commit e2c81a9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/browser/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ patchXHR(_global);

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

interface XHROptions extends TaskData {
target: any;
Expand All @@ -63,13 +64,20 @@ function patchXHR(window: any) {

function scheduleTask(task: Task) {
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) {
task.invoke();
}
}
});
};
data.target.addEventListener('readystatechange', newListener);

var storedTask: Task = data.target[XHR_TASK];
if (!storedTask) {
data.target[XHR_TASK] = 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 e2c81a9

Please sign in to comment.