Explorar el Código

Replace $watch(state) with explicit event registry

Danilo Bargen hace 7 años
padre
commit
b468e0195b
Se han modificado 3 ficheros con 27 adiciones y 8 borrados
  1. 4 7
      src/controllers/status.ts
  2. 18 1
      src/services/state.ts
  3. 5 0
      src/threema.d.ts

+ 4 - 7
src/controllers/status.ts

@@ -69,13 +69,10 @@ export class StatusController {
         this.webClientService = webClientService;
         this.controllerService = controllerService;
 
-        // Watch state changes
-        $scope.$watch(
-            () => stateService.state,
-            (newValue: threema.GlobalConnectionState, oldValue: threema.GlobalConnectionState) => {
-                if (oldValue !== newValue) {
-                    this.onStateChange(newValue, oldValue);
-                }
+        // Register event handlers
+        this.stateService.evtGlobalConnectionStateChange.attach(
+            (stateChange: threema.GlobalConnectionStateChange) => {
+                this.onStateChange(stateChange.state, stateChange.prevState);
             },
         );
     }

+ 18 - 1
src/services/state.ts

@@ -36,6 +36,7 @@ export class StateService {
 
     // Events
     public evtConnectionBuildupStateChange = new AsyncEvent<threema.ConnectionBuildupStateChange>();
+    public evtGlobalConnectionStateChange = new AsyncEvent<threema.GlobalConnectionStateChange>();
 
     // Connection states
     public signalingConnectionState: saltyrtc.SignalingState;
@@ -49,7 +50,7 @@ export class StateService {
 
     // Global connection state
     private stage: Stage;
-    public state: threema.GlobalConnectionState;
+    private _state: threema.GlobalConnectionState;
     public wasConnected: boolean;
 
     public static $inject = ['$log', '$interval'];
@@ -59,6 +60,22 @@ export class StateService {
         this.reset();
     }
 
+    /**
+     * Getters and setters for global connection state.
+     */
+    public get state(): threema.GlobalConnectionState {
+        return this._state;
+    }
+    public set state(state: threema.GlobalConnectionState) {
+        const prevState = this._state;
+        if (prevState === state) {
+            // No need to dispatch any events
+            return;
+        }
+        this._state = state;
+        this.evtGlobalConnectionStateChange.post({state: state, prevState: prevState});
+    }
+
     /**
      * Signaling connection state.
      */

+ 5 - 0
src/threema.d.ts

@@ -415,6 +415,11 @@ declare namespace threema {
         Error = 'error',
     }
 
+    interface GlobalConnectionStateChange {
+        state: GlobalConnectionState;
+        prevState: GlobalConnectionState;
+    }
+
     /**
      * Type of message to be sent to a receiver.
      */