Sfoglia il codice sorgente

replace self with this - arrow function
replace setZeroTimeout(func) with setTimeout(func,0)

afrokick 6 anni fa
parent
commit
ebe9ac08b5
5 ha cambiato i file con 77 aggiunte e 131 eliminazioni
  1. 24 31
      lib/dataconnection.ts
  2. 6 6
      lib/negotiator.ts
  3. 21 25
      lib/peer.ts
  4. 26 34
      lib/socket.ts
  5. 0 35
      lib/util.ts

+ 24 - 31
lib/dataconnection.ts

@@ -70,12 +70,10 @@ export class DataConnection extends BaseConnection {
       this.dataChannel.binaryType = "arraybuffer";
     }
 
-    const self = this;
-
-    this.dataChannel.onopen = function () {
+    this.dataChannel.onopen = () => {
       util.log("Data channel connection success");
-      self._open = true;
-      self.emit(ConnectionEventType.Open);
+      this._open = true;
+      this.emit(ConnectionEventType.Open);
     };
 
     // Use the Reliable shim for non Firefox browsers
@@ -84,17 +82,17 @@ export class DataConnection extends BaseConnection {
     }
 
     if (this._reliable) {
-      this._reliable.onmessage = function (msg) {
-        self.emit(ConnectionEventType.Data, msg);
+      this._reliable.onmessage = (msg) => {
+        this.emit(ConnectionEventType.Data, msg);
       };
     } else {
-      this.dataChannel.onmessage = function (e) {
-        self._handleDataMessage(e);
+      this.dataChannel.onmessage = (e) => {
+        this._handleDataMessage(e);
       };
     }
-    this.dataChannel.onclose = function (e) {
-      util.log("DataChannel closed for:", self.peer);
-      self.close();
+    this.dataChannel.onclose = (e) => {
+      util.log("DataChannel closed for:", this.peer);
+      this.close();
     };
   }
 
@@ -103,17 +101,15 @@ export class DataConnection extends BaseConnection {
     let data = e.data;
     const datatype = data.constructor;
 
-    if (
-      this.serialization === SerializationType.Binary ||
-      this.serialization === SerializationType.BinaryUTF8
-    ) {
-      if (datatype === Blob) {
-        const self = this;
+    const isBinarySerialization = this.serialization === SerializationType.Binary ||
+      this.serialization === SerializationType.BinaryUTF8;
 
+    if (isBinarySerialization) {
+      if (datatype === Blob) {
         // Datatype should never be blob
-        util.blobToArrayBuffer(data, function (ab) {
+        util.blobToArrayBuffer(data, (ab) => {
           data = util.unpack(ab);
-          self.emit(ConnectionEventType.Data, data);
+          this.emit(ConnectionEventType.Data, data);
         });
         return;
       } else if (datatype === ArrayBuffer) {
@@ -209,18 +205,16 @@ export class DataConnection extends BaseConnection {
         return;
       }
 
-      const self = this;
-
       // DataChannel currently only supports strings.
       if (!util.supports.sctp) {
-        util.blobToBinaryString(blob, function (str) {
-          self._bufferedSend(str);
+        util.blobToBinaryString(blob, (str) => {
+          this._bufferedSend(str);
         });
       } else if (!util.supports.binaryBlob) {
         // We only do this if we really need to (e.g. blobs are not supported),
         // because this conversion is costly.
-        util.blobToArrayBuffer(blob, function (ab) {
-          self._bufferedSend(ab);
+        util.blobToArrayBuffer(blob, (ab) => {
+          this._bufferedSend(ab);
         });
       } else {
         this._bufferedSend(blob);
@@ -244,13 +238,12 @@ export class DataConnection extends BaseConnection {
     } catch (e) {
       this._buffering = true;
 
-      const self = this;
-
-      setTimeout(function () {
+      setTimeout(() => {
         // Try again.
-        self._buffering = false;
-        self._tryBuffer();
+        this._buffering = false;
+        this._tryBuffer();
       }, 100);
+
       return false;
     }
 

+ 6 - 6
lib/negotiator.ts

@@ -129,7 +129,7 @@ class Negotiator {
     // ICE CANDIDATES.
     util.log("Listening for ICE candidates.");
 
-    peerConnection.onicecandidate = function (evt) {
+    peerConnection.onicecandidate = (evt) => {
       if (evt.candidate) {
         util.log("Received ICE candidates for:", peerId);
         provider.socket.send({
@@ -144,7 +144,7 @@ class Negotiator {
       }
     };
 
-    peerConnection.oniceconnectionstatechange = function () {
+    peerConnection.oniceconnectionstatechange = () => {
       switch (peerConnection.iceConnectionState) {
         case "failed":
           util.log(
@@ -177,7 +177,7 @@ class Negotiator {
     util.log("Listening for data channel");
     // Fired between offer and answer, so options should already be saved
     // in the options hash.
-    peerConnection.ondatachannel = function (evt) {
+    peerConnection.ondatachannel = (evt) => {
       util.log("Received data channel");
 
       const dataChannel = evt.channel;
@@ -190,8 +190,8 @@ class Negotiator {
 
     // MEDIACONNECTION.
     util.log("Listening for remote stream");
-    const self = this;
-    peerConnection.ontrack = function (evt) {
+
+    peerConnection.ontrack = (evt) => {
       util.log("Received remote stream");
 
       const stream = evt.streams[0];
@@ -200,7 +200,7 @@ class Negotiator {
       if (connection.type === ConnectionType.Media) {
         const mediaConnection = <MediaConnection>connection;
 
-        self._addStreamToMediaConnection(stream, mediaConnection);
+        this._addStreamToMediaConnection(stream, mediaConnection);
       }
     };
   }

+ 21 - 25
lib/peer.ts

@@ -166,28 +166,26 @@ export class Peer extends EventEmitter {
       this._options.wsport
     );
 
-    const self = this;
-
     this.socket.on(SocketEventType.Message, data => {
-      self._handleMessage(data);
+      this._handleMessage(data);
     });
 
     this.socket.on(SocketEventType.Error, error => {
-      self._abort(PeerErrorType.SocketError, error);
+      this._abort(PeerErrorType.SocketError, error);
     });
 
     this.socket.on(SocketEventType.Disconnected, () => {
       // If we haven't explicitly disconnected, emit error and disconnect.
-      if (!self.disconnected) {
-        self.emitError(PeerErrorType.Network, "Lost connection to server.");
-        self.disconnect();
+      if (!this.disconnected) {
+        this.emitError(PeerErrorType.Network, "Lost connection to server.");
+        this.disconnect();
       }
     });
 
-    this.socket.on(SocketEventType.Close, function () {
+    this.socket.on(SocketEventType.Close, () => {
       // If we haven't explicitly disconnected, emit error.
-      if (!self.disconnected) {
-        self._abort(
+      if (!this.disconnected) {
+        this._abort(
           PeerErrorType.SocketClosed,
           "Underlying socket is already closed."
         );
@@ -412,10 +410,9 @@ export class Peer extends EventEmitter {
   }
 
   private _delayedAbort(type: PeerErrorType, message): void {
-    const self = this;
-    util.setZeroTimeout(function () {
-      self._abort(type, message);
-    });
+    setTimeout(() => {
+      this._abort(type, message);
+    }, 0);
   }
 
   /**
@@ -490,20 +487,19 @@ export class Peer extends EventEmitter {
    *  disconnected. It also cannot reconnect to the server.
    */
   disconnect(): void {
-    const self = this;
-    util.setZeroTimeout(function () {
-      if (!self.disconnected) {
-        self._disconnected = true;
-        self._open = false;
-        if (self.socket) {
-          self.socket.close();
+    setTimeout(() => {
+      if (!this.disconnected) {
+        this._disconnected = true;
+        this._open = false;
+        if (this.socket) {
+          this.socket.close();
         }
 
-        self.emit(PeerEventType.Disconnected, self.id);
-        self._lastServerId = self.id;
-        self._id = null;
+        this.emit(PeerEventType.Disconnected, this.id);
+        this._lastServerId = this.id;
+        this._id = null;
       }
-    });
+    }, 0);
   }
 
   /** Attempts to reconnect with the same ID. */

+ 26 - 34
lib/socket.ts

@@ -20,17 +20,15 @@ class HttpRequest {
   }
 
   constructor(readonly streamIndex: number, private readonly _httpUrl: string) {
-    const self = this;
-
     this._xmlHttpRequest.onerror = () => {
-      self._onError(self);
+      this._onError(self);
     };
 
     this._xmlHttpRequest.onreadystatechange = () => {
-      if (self.needsClearPreviousRequest()) {
-        self.clearPreviousRequest();
-      } else if (self.isSuccess()) {
-        self._onSuccess(self);
+      if (this.needsClearPreviousRequest()) {
+        this.clearPreviousRequest();
+      } else if (this.isSuccess()) {
+        this._onSuccess(self);
       }
     };
   }
@@ -139,9 +137,7 @@ export class Socket extends EventEmitter {
 
     this._socket = new WebSocket(this._wsUrl);
 
-    const self = this;
-
-    this._socket.onmessage = function (event) {
+    this._socket.onmessage = (event) => {
       let data;
 
       try {
@@ -150,31 +146,31 @@ export class Socket extends EventEmitter {
         util.log("Invalid server message", event.data);
         return;
       }
-      self.emit(SocketEventType.Message, data);
+      this.emit(SocketEventType.Message, data);
     };
 
-    this._socket.onclose = function (event) {
+    this._socket.onclose = (event) => {
       util.log("Socket closed.", event);;
 
-      self._disconnected = true;
-      self.emit(SocketEventType.Disconnected);
+      this._disconnected = true;
+      this.emit(SocketEventType.Disconnected);
     };
 
     // Take care of the queue of connections if necessary and make sure Peer knows
     // socket is open.
-    this._socket.onopen = function () {
-      if (self._timeout) {
-        clearTimeout(self._timeout);
-        setTimeout(function () {
-          self._httpRequest.abort();
-          self._httpRequest = null;
+    this._socket.onopen = () => {
+      if (this._timeout) {
+        clearTimeout(this._timeout);
+        setTimeout(() => {
+          this._httpRequest.abort();
+          this._httpRequest = null;
         }, 5000);
       }
 
-      self._sendQueuedMessages();
+      this._sendQueuedMessages();
       util.log("Socket open");
 
-      self._wsPingTimer = setTimeout(function () { self._sendHeartbeat() }, self.WEB_SOCKET_PING_INTERVAL);
+      this._wsPingTimer = setTimeout(() => { this._sendHeartbeat() }, this.WEB_SOCKET_PING_INTERVAL);
     };
   }
 
@@ -212,9 +208,7 @@ export class Socket extends EventEmitter {
     const message = JSON.stringify(data);
     this._socket.send(message);
 
-    const self = this;
-
-    this._wsPingTimer = setTimeout(function () { self._sendHeartbeat() }, this.WEB_SOCKET_PING_INTERVAL);
+    this._wsPingTimer = setTimeout(() => { this._sendHeartbeat() }, this.WEB_SOCKET_PING_INTERVAL);
   }
 
   /** Handles onreadystatechange response as a stream. */
@@ -261,16 +255,14 @@ export class Socket extends EventEmitter {
   }
 
   private _setHTTPTimeout() {
-    const self = this;
-
-    this._timeout = setTimeout(function () {
-      if (!self._wsOpen()) {
-        const oldHttp = self._httpRequest;
-        self._startXhrStream(oldHttp.streamIndex + 1);
-        self._httpRequest.previousRequest = oldHttp;
+    this._timeout = setTimeout(() => {
+      if (!this._wsOpen()) {
+        const oldHttp = this._httpRequest;
+        this._startXhrStream(oldHttp.streamIndex + 1);
+        this._httpRequest.previousRequest = oldHttp;
       } else {
-        self._httpRequest.abort();
-        self._httpRequest = null;
+        this._httpRequest.abort();
+        this._httpRequest = null;
       }
     }, this.HTTP_TIMEOUT);
   }

+ 0 - 35
lib/util.ts

@@ -255,41 +255,6 @@ export class util {
   static warn(...rest): void { }
   static error(...rest): void { }
 
-  static setZeroTimeout = (global => {
-    const timeouts = [];
-    const messageName = "zero-timeout-message";
-
-    // Like setTimeout, but only takes a function argument.	 There's
-    // no time argument (always zero) and no arguments (you have to
-    // use a closure).
-    function setZeroTimeoutPostMessage(fn) {
-      timeouts.push(fn);
-      global.postMessage(messageName, "*");
-    }
-
-    function handleMessage(event) {
-      if (event.source === global && event.data === messageName) {
-        if (event.stopPropagation) {
-          event.stopPropagation();
-        }
-        if (timeouts.length) {
-          timeouts.shift()();
-        }
-      }
-    }
-
-    if (global.addEventListener) {
-      global.addEventListener("message", handleMessage, true);
-    }
-    // @ts-ignore
-    else if (global.attachEvent) {
-      // @ts-ignore
-      global.attachEvent("onmessage", handleMessage);
-    }
-
-    return setZeroTimeoutPostMessage;
-  })(window);
-
   // Binary stuff
 
   private static _dataCount = 1;