How to unsubscribe from a socket.io subscription?

前端 未结 11 1329
长发绾君心
长发绾君心 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:01

    To add to @Andrew Magee, here is an example of unsubscribing socket.io events in Angular JS, and of course works with Vanilla JS:

    function handleCarStarted ( data ) { // Do stuff }
    function handleCarStopped ( data ) { // Do stuff }
    

    Listen for events:

    var io = $window.io(); // Probably put this in a factory, not controller instantiation
    io.on('car.started', handleCarStarted);
    io.on('car.stopped', handleCarStopped);
    
    
    $scope.$on('$destroy', function () {
        io.removeListener('car.started', handleCarStarted);
        io.removeListener('car.stopped', handleCarStopped);
    });
    

提交回复
热议问题