zoukankan      html  css  js  c++  java
  • [Javascript] Broadcaster + Operator + Listener pattern -- 13. Repeat When Done with a Repeat Operator

    Apps often have scenarios where one event controls another. In operators, this requires passing one broadcaster in and using it to control another broadcaster. You can think, "when this broadcaster fires, do that with the other broadcaster". This lesson covers using one broadcaster to control when another broadcaster repeats.

    import { addListener, done, forOf } from "./broadcasters";
    
    const log = console.log;
    
    // only when listener receive DONE event
    // then broadcaster should trigger the listener again
    // otherwise, keep emit value
    let repeat = (broadcaster) => (listener) => {
      let cancel;
      let repeatListener = (value) => {
        // when it is doen event
        if (value === done) {
          // because it is repeated event
          // need to cancel previous one
          if (cancel) {
            cancel();
          }
          // broadcaster should trigger the listener again
          cancel = broadcaster(repeatListener);
          return;
        }
        // otherwise, keep emitting value
        listener(value);
      };
      cancel = broadcaster(repeatListener);
    
      return () => cancel();
    };
    
    // Only when 'whenBroadcater' happen then do the repeat logic
    let repeatWhen = (whenBroadcaster) => (mainBroadcaster) => (listener) => {
      let mainCancel;
      let whenCancel;
      let repeatListener = (value) => {
        if (value === done) {
          if (mainCancel) {
            mainCancel();
          }
          whenCancel = whenBroadcaster(() => {
           // cancel previous when broadcaster 
            whenCancel();
            mainCancel = mainBroadcaster(repeatListener);
          });
        }
        listener(value);
      };
      mainCancel = mainBroadcaster(repeatListener);
    
      return () => {
        mainCancel();
        whenCancel();
      };
    };
    
    const inputClick = addListener("#input", "click");
    const printCat = forOf("cat");
    const repeatCatOnClick = repeatWhen(inputClick)(printCat);
    const cancel = repeatCatOnClick(log);
    
    setTimeout(() => {
      cancel();
    }, 3000);
  • 相关阅读:
    centos7 做rails 执行rails server 报错
    centos 7 安装 rvm 超时
    centos7 打造基于python语言Selenium2自动化开发环境
    RubyMine8 安装
    linux 下安装 RZ SZ命令 以及使用
    centos 7.2 安装mysql 修改 初始密码
    win10系统配置FTP
    Windows环境安装MySQL8.0.11
    IntelliJ IDEA 2017 上传本地项目至码云
    IntelliJ IDEA 2017.3 搭建一个多模块的springboot项目(三)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13921149.html
Copyright © 2011-2022 走看看