我怎样才能停止收听 BroadcastChannel

How can I stop listening to BroadcastChannel

我创建了这个广播服务。 当动态生成 addEventListener 的事件处理程序时,如何添加 BroadcastChannel.removeEventListener 方法?

@Injectable({
  providedIn: 'root'
})
export class BroadcastService {
  private consumer: BroadcastChannel;
  private producer: BroadcastChannel;

  constructor() {
    this.consumer = new BroadcastChannel('pluginGlobalEventBus');
    this.producer = new BroadcastChannel('pluginGlobalEventBus');
  }

  /**
   * broadcast a message
   */
  postMessage(message: any): void {
    this.producer.postMessage(message);
  }

  /**
   * listen to a broadcast
   */
  addEventListener(eventName, listener): void {
    this.consumer.addEventListener('message', event => {
      if (event.data.name === eventName) {
        listener(event.data.value);
      }
    });
  }

  /**
   * stop broadcasting
   */
  close(): void {
    this.consumer.close();
    this.producer.close();
  }
}

您可以将事件侦听器存储在 private 数组中并迭代这些侦听器以将其删除。

private eventListeners = [] // To store event listeners generated dynamically

addEventListener(eventName, listener): void {
    const eventListener = event => {
      if (event.data.name === eventName) {
        listener(event.data.value);
      }
    };
    this.consumer.addEventListener('message', eventListener);
    this.eventListeners.push(eventListener); // Store event listener
}

removeEventListener() {
  // Iterate through all stored event listeners to remove them
  this.eventListeners.forEach((listener) => {
    this.consumer.removeEventListener('message', listener); 
  });
  // Do not forget to clear listeners array
  this.eventListeners = [];
}

如果出于某种原因,您一次只需要删除一个侦听器,那么我想您可以使用 Map 来存储事件侦听器,并在 addEventListener 上生成一个唯一 ID .

很简单:

// Connect to a channel
var bc = new BroadcastChannel('test_channel');

// More operations (like postMessage, …)

// When done, disconnect from the channel
bc.close();