简体   繁体   中英

NodeJS remove event listener for bound function

I know the issue I am facing, but not sure how to solve it. Basically I have a Room class that stores Clients . When they join the room, handlers are attached to them. When they leave, handlers are removed. However, because I am using bind (and don't mind changing it if possible) I can't figure out how to call off and pass the correct function reference.

class Room {
   atttachClientHandlers(client){
      client.on('data', this.handleData.bind(this, client);
   }
   detachClientHandlers(client){
      client.off('data', this.handleData);
   }
   handleData(client, data){
      // do something
   }
}

let client = new Client();
let room = new Room();
room.attachClientHanlders(client); // ok
room.detachClientHandlers(client); // never detaches it

I don't see anywhere I can store the handler for this client, or how I can give a name to the function callback.

The main thing to do is to store the function reference when it's created, like so:

   attachClientHandlers(client){
      this.boundHandleData = this.handleData.bind(this, client);
      client.on('data', this.boundHandleData);
   }

Your detach method can then pass this reference to off if the reference exists:

detachClientHandlers(client) {
   if (this.boundHandleData) {
      client.off('data', this.boundHandleData);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM