How to unsubscribe from a socket.io subscription?

前端 未结 11 1323
长发绾君心
长发绾君心 2020-11-30 02:00

Suppose there are objects making subscriptions to a socket server like so:

socket.on(\'news\', obj.socketEvent)

These objects have a short life

11条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 02:15

    Since I had a spot of troubles making this work figured I'd chime in here as well, along with a nice updated answer for 2017. Thanks to @Pjotr for pointing out that it has to be the same callback instance.

    Example with Angular2 TypeScript in a socket-io.subscriber service. Note the "newCallback" wrapper

      private subscriptions: Array<{
        key: string,
        callback: Function
      }>;
    
      constructor() {
        this.subscriptions = [];
      }
    
      subscribe(key: string, callback: Function) {
        let newCallback = (response) => callback(response);
        this.socket.on(key, newCallback);
        return this.subscriptions.push({key: key, callback: newCallback}) - 1;
      }
    
      unsubscribe(i: number) {
        this.socket.removeListener(this.subscriptions[i].key, this.subscriptions[i].callback);
      }
    

提交回复
热议问题