What is the best method for subscribing to and unsubscribing from an event?

There is event subscription using an anonymous function:

this.entity.on('eventName', () => {}, this);
this.entity.on('eventName', function () {}, this);

In this case, how can you unsubscribe from all entity subscriptions for the given event?
Will it work, and is this method acceptable?

const self = this;
this.on('destroy', function () {
    self.entity.off('eventName');
});

Should I use ‘once’ for the ‘destroy’ event, or is ‘on’ sufficient?

const self = this;
this.once('destroy', function () {
    self.entity.off('eventName');
});

Hi @SARJ,

You need to keep a reference of your anonymous function:

const myMethod = () => {};

this.entity.on('eventName', myMethod);

// later remove the event just for this method
this.entity.off('eventName', myMethod);

Ofcourse you can still call the off() without any argument, and it will handle both this method and any other attached with this eventName. It depends on what you are trying to do.

Can you call it like this, without specifying functions, to unsubscribe from any events of the entity?

this.entity.off('eventName');
1 Like

That will unsubscribe any events named eventName for this entity.

If you want to unsubscribe from any events, whatever their name is, use:

this.entity.off();

Be careful with this last one, there may be internal events the PlayCanvas engine uses that you may be turning off.

With the next engine release, you will be able to do it like this:

const event = this.entity.on('eventName', myMethod);

// then later
event.off();

More details:

3 Likes

@Leonidas I want to unsubscribe all events called ‘eventName’ from the entity, so I think this is a better:
this.entity.off('eventName');

Indeed, do not need to unsubscribe everything.

1 Like

@LeXXik Cool :+1:

So I can call the following construct in the future?

const event = this.entity.on('eventName', myMethod);

this.once('destroy', function () {
    event.off();
});

Should I use ‘once’ for the ‘destroy’ event, or is ‘on’ sufficient?

I would gather it’s the same, given the destroy event will fire once in the lifetime of the entity. But I haven’t fully tested it and most examples use on.

1 Like