Skip to content

Commit

Permalink
Implement EventTarget interface for WebSocket.
Browse files Browse the repository at this point in the history
Summary: close #2583Closes #2599

Reviewed By: @​svcscm

Differential Revision: D2498641

Pulled By: @vjeux
  • Loading branch information
leeyeh authored and facebook-github-bot-6 committed Oct 2, 2015
1 parent 14d2b0e commit 626b551
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
30 changes: 26 additions & 4 deletions Libraries/WebSocket/WebSocket.ios.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,19 @@ var RCTWebSocketManager = require('NativeModules').WebSocketManager;

var WebSocketBase = require('WebSocketBase');

class Event {
constructor(type) {
this.type = type.toString();
}
}

class MessageEvent extends Event {
constructor(type, eventInitDict) {
super(type);
Object.assign(this, eventInitDict);
}
}

var WebSocketId = 0;

class WebSocket extends WebSocketBase {
Expand Down Expand Up @@ -58,9 +71,11 @@ class WebSocket extends WebSocketBase {
if (ev.id !== id) {
return;
}
this.onmessage && this.onmessage({
var event = new MessageEvent('message', {
data: ev.data
});
this.onmessage && this.onmessage(event);
this.dispatchEvent(event);
}.bind(this)
),
RCTDeviceEventEmitter.addListener(
Expand All @@ -70,7 +85,9 @@ class WebSocket extends WebSocketBase {
return;
}
this.readyState = this.OPEN;
this.onopen && this.onopen();
var event = new Event('open');
this.onopen && this.onopen(event);
this.dispatchEvent(event);
}.bind(this)
),
RCTDeviceEventEmitter.addListener(
Expand All @@ -80,7 +97,9 @@ class WebSocket extends WebSocketBase {
return;
}
this.readyState = this.CLOSED;
this.onclose && this.onclose(ev);
var event = new Event('close');
this.onclose && this.onclose(event);
this.dispatchEvent(event);
this._unregisterEvents();
RCTWebSocketManager.close(id);
}.bind(this)
Expand All @@ -91,7 +110,10 @@ class WebSocket extends WebSocketBase {
if (ev.id !== id) {
return;
}
this.onerror && this.onerror(new Error(ev.message));
var event = new Event('error');
event.message = ev.message;
this.onerror && this.onerror(event);
this.dispatchEvent(event);
this._unregisterEvents();
RCTWebSocketManager.close(id);
}.bind(this)
Expand Down
5 changes: 4 additions & 1 deletion Libraries/WebSocket/WebSocketBase.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@
*/
'use strict';

var EventTarget = require('event-target-shim');

/**
* Shared base for platform-specific WebSocket implementations.
*/
class WebSocketBase {
class WebSocketBase extends EventTarget {
CONNECTING: number;
OPEN: number;
CLOSING: number;
Expand All @@ -33,6 +35,7 @@ class WebSocketBase {
url: ?string;

constructor(url: string, protocols: ?any) {
super();
this.CONNECTING = 0;
this.OPEN = 1;
this.CLOSING = 2;
Expand Down

0 comments on commit 626b551

Please sign in to comment.