From f109cbe80bded17e749c930c64a90ed4250f8ee9 Mon Sep 17 00:00:00 2001 From: Hristo Deshev Date: Mon, 15 Jun 2015 14:28:16 +0300 Subject: [PATCH] Support onload/onerror events on XMLHttpRequest. --- apps/tests/http-tests.ts | 18 ++++++++++++++++++ declarations.d.ts | 3 +++ http/http.ts | 19 ++++++++++++++++--- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/apps/tests/http-tests.ts b/apps/tests/http-tests.ts index fc1d144e3..1f3797e0f 100644 --- a/apps/tests/http-tests.ts +++ b/apps/tests/http-tests.ts @@ -598,3 +598,21 @@ export var test_XMLHttpRequest_requestShouldBePossibleAfterAbort = function (don xhr.send(JSON.stringify({ MyVariableOne: "ValueOne", MyVariableTwo: "ValueTwo" })); }; + +export function test_raises_onload_Event(done) { + let xhr = new XMLHttpRequest(); + xhr.onload = () => { + done(null); + } + xhr.open("GET", "https://httpbin.org/get"); + xhr.send(); +} + +export function test_raises_onerror_Event(done) { + let xhr = new XMLHttpRequest(); + xhr.onerror = () => { + done(null); + } + xhr.open("GET", "https://no-such-domain-httpbin.org"); + xhr.send(); +} diff --git a/declarations.d.ts b/declarations.d.ts index 88412183b..bcb43448a 100644 --- a/declarations.d.ts +++ b/declarations.d.ts @@ -38,6 +38,9 @@ declare class XMLHttpRequest { readyState: number; responseText: string; status: number; + + onload: () => void; + onerror: () => void; } /** diff --git a/http/http.ts b/http/http.ts index 0bdc7bac6..da8b385d7 100644 --- a/http/http.ts +++ b/http/http.ts @@ -39,6 +39,9 @@ export class XMLHttpRequest { public LOADING = 3; public DONE = 4; + public onload: () => void; + public onerror: () => void; + private _options: definition.HttpRequestOptions; private _readyState: number; private _status: number; @@ -112,8 +115,9 @@ export class XMLHttpRequest { } }).catch(e => { - this._errorFlag = true; - }); + this._errorFlag = true; + this._setReadyState(this.DONE); + }); } } @@ -167,6 +171,15 @@ export class XMLHttpRequest { this.onreadystatechange(); } } + + if (this._readyState === this.DONE) { + if (this._errorFlag && types.isFunction(this.onerror)) { + this.onerror(); + } + if (!this._errorFlag && types.isFunction(this.onload)) { + this.onload(); + } + } } get responseText(): string { @@ -230,4 +243,4 @@ var statuses = { 503: "Service Unavailable", 504: "Gateway Timeout", 505: "HTTP Version Not Supported" -}; \ No newline at end of file +};