timonsku
timonsku

Reputation: 1258

How should I deal with event handlers of objects that I want to delete?

I was wondering what is the proper and least verbose way to deal with objects that have event handlers registered.

Lets take this example:

const mqtt = require('mqtt')
var users = []

function createClient(){
var user = { 'name': 'barney', 'age': 36, 'client': client: mqtt.connect('mqtt://127.0.0.1'), 'active': false }
user.client.on("message",messageHandler.bind(user))
users.push(user)
}

function messageHandler(topic, message){
console.log(`'User' ${this.name} received ${message} on ${topic}`)
}

createClient()
delete users[0].client
users = []

Now the client object is gone but the event handler seems to be still alive as I now get an error thrown because user is undefined.

I would have assumed that the garbage collector would take care of event handlers of objects that don't exist anymore.

Edit: It seems I simplified too much. I changed the code to reflect an actual existing object. mqtt comes from mqtt.js

It seems it is important what the object does/is. I would appreciate an answer that explains why that is as it seems to be very related as to why I am having my issue. I don't need help with fixing my code, I want to better understand how objects and event handlers work and how the garbage collection deals with the. From the resources I read so far the behaviour I'm getting seems confusing to me.

Upvotes: 0

Views: 94

Answers (1)

Bonlou
Bonlou

Reputation: 472

If you are brought to do this often, you can create your own function to handle this case. For example :

const unbindAndDelete = (element, event = 'bark', handler = 'barkHandler') => {
  element.removeEventListener(event, handler);
  delete element;
}

But be sure to pass to it a valid element to delete, i.e. an object property. Javascript will not let you do this on variable.

Upvotes: 4

Related Questions