GetStream.io Chat API - Stop Listening for channel Events in Stream

Viewed 493

I'm confused by the documentation on how to stop listening for channel events in JS using the Stream Chat API. As per the docs:

// remove the handler for all "message.new" events on the channel
channel.off("message.new", myChannelEventHandler);

What is myChannelEventHandler?

My channel.on looks like this, from the example Angular application:

this.channel.on('message.new', event => {
    this.messages = [...this.messages, event.message];
});

This is the only time myChannelEventHandler ever referenced in the docs, any guidance would be appreciated.

2 Answers

Thanks to Taplar, I've gotten this working. Solution is as simple as this:

Define a message event handler, and create a property for the Angular component class:

messageEventHandler = event => {
    this.messages = [...this.messages, event.message];
};

Use event handler for channel on:

this.channel.on('message.new', this.messageEventHandler)

Use the same event handler for channel off:

this.channel.off('message.new', this.messageEventHandler)

I would suggest refactoring the code so you can reference your function inside channel.off. This is more a JavaScript language question

const myChannelEventHandler = event => {
    this.messages = [...this.messages, event.message];
}

this.channel.on('message.new', myChannelEventHandler);

// remove the handler for all "message.new" events on the channel
// Apply this whenever you need
channel.off("message.new", myChannelEventHandler);
Related