Skip to content Skip to sidebar Skip to footer

Socket.io Client Listening To Same Event Multiple Times After Refresh

I got a master page which contains a table of items and the table data will be refreshed continuously after a successful socket.io connection with the server. upon clicking an item

Solution 1:

//updates child view.
socket.on('childData', function (id) {
    var data = self.FindModule(id);
    statusPacketTimer = setInterval(function () {
        socket.emit('moduleData', self.LocateStatusPacket(id));
    }, 1000);
});

in this code the setInterval continous. if the child view rendering is triggered via socket.emit('moduleData', self.LocateStatusPacket(id));

then it is rendering every second

Solution 2:

I had the same issue. Before each instance of socket.on(endpoint, callback), precede it with socket.off(endpoint, callback).

<script>const dataCallback = function (message) {
        $('#mainTable').find('tr:gt(0)').remove();
        cupdateTable(message);
    };
    socket.off('data', dataCallback); // Removes existing handler, if present.
    socket.on('data', dataCallback);
</script>

This removes only the dataCallback callback from the data endpoint. If you want to delete all callback functions associated with the data endpoint (it's perfectly legal to have more than one), then you can omit the callback argument and simply do

<script>const dataCallback = function (message) {
        $('#mainTable').find('tr:gt(0)').remove();
        cupdateTable(message);
    };
    socket.off('data'); // Removes ALL existing handlers for this endpoint.
    socket.on('data', dataCallback);
</script>

Post a Comment for "Socket.io Client Listening To Same Event Multiple Times After Refresh"