pushState Listener triggered multiple times

I am trying to listen to pushState events in my plugin code. for now I am listening and logging.

I register my listener on the onStart function. But every time the state changes the listener is triggered multiple times instead of once.

Can someone tell me what is going wrong here?

// Plugin has started
AutoVol.prototype.onStart = function() {
    const self = this;
	
	const defer=libQ.defer();

	self.astart = Date.now();

	socket.emit("getState", "");

	socket.on("pushState", (state) => {
		self.statusChanged(state);
	});

	// Once the Plugin has successfull started resolve the promise
	defer.resolve();

    return defer.promise;
};

Hey @netrikkann,

The issue is listener accumulation. Each time onStart runs, you add another socket.on listener without removing previous ones. After plugin restarts or multiple starts, you end up with duplicate listeners all firing on the same event.

Fix: Remove the listener in onStop.

AutoVol.prototype.onStart = function() {
    const self = this;
    const defer = libQ.defer();

    self.astart = Date.now();

    // Store reference to the bound function for later removal
    self.pushStateHandler = function(state) {
        self.statusChanged(state);
    };

    socket.emit("getState", "");
    socket.on("pushState", self.pushStateHandler);

    defer.resolve();
    return defer.promise;
};

AutoVol.prototype.onStop = function() {
    const self = this;
    const defer = libQ.defer();

    // Remove the listener
    socket.off("pushState", self.pushStateHandler);

    defer.resolve();
    return defer.promise;
};

Key points:

  • Store the handler function reference in self.pushStateHandler
  • Use socket.off() in onStop to remove that specific listener
  • This prevents listener accumulation across plugin restarts

Alternative: Use socket.once() if you only need the state once, but for continuous monitoring you need the on/off pattern shown above.

Kind Regards,

@netrikkann,

One request: please consolidate your plugin development questions into a single thread - something like “Learning Plugin Development” or similar. It keeps related discussion together and helps others learning the same things find the answers more easily.

Kind Regards,