[Javascript] Broadcaster + Operator + Listener pattern -- 2 Unsubscribe from Broadcaster

Because Javascript has inconsistent way to cleanup the lisenters:

removeEventListener(button, "click")
clearnTimeout(id)

 

We can implement a contract to provide a consistent way to do unsubscribe:

let button = document.getElementById("button");

let createEventBroadcaster = (element, eventType) => (listerner) => {
  element.addEventListener(eventType, listerner);
};

let buttonClick = (listener) => {
  createEventBroadcaster(button, "click")(listener);
  // implement a contract to stop the event listener
  return () => {
    button.removeEventListener("click", listener);
  };
};

Return a function to clean up.

 

Usage

let stopAfter3Times = (broadcater) => (listener) => {
  let i = 0;
  let stop = broadcater((value) => {
    listener(value);
    i++;
    if (i === 3) stop();
  });
};

stopAfter3Times(buttonClick)(log);

 

 

Implement a stopWhen operator:

let interval = (listener) => {
  let id = setInterval(() => {
    listener("hello");
  }, 1000);

  return () => {
    clearInterval(id);
  };
};

let stopWhen = (stopperBroadcaster) => (broadcaster) => (listener) => {
  const stop = broadcaster(listener);

  stopperBroadcaster(() => {
    stop();
  });
};

stopWhen(buttonClick)(interval)(log);

 

posted @ 2020-09-29 19:12  Zhentiw  阅读(141)  评论(0编辑  收藏  举报