zoukankan      html  css  js  c++  java
  • [Javascript] Broadcaster + Operator + Listener pattern -- 7. Create a broadcaster forOf

    The patterns we've established can also work well with plain old Objects and Arrays. We just have to capture the behavior of accessing those values inside of our broadcaster so the values can be passed down into a listener.

    We will create a custom forOf function to implement an scenario where we can type out a letter every second, this is basically grouping the behavior of some of our broadcasters.

    We will call our forOf function a broadcaster creator. This function will take two arguments, an Iterable and a listener and, as our current pattern, we will use curry to handle the arguments. Our forOf will just iterate over the iterable argument and will call the listener in each iteration.

    let forOf = curry((iterable, listener) => {
      for (let i of iterable) {
        listener(i)
      }
    })

    The question is how to implement the cancel behavor?

    We can wrap with setTimeout:

    let forOf = curry((iterable, listener) => {
      let id = setTimeout(() => {
        for (let i of iterable) {
          listener(i)
        }
      }, 0)
      return () => {
        clearTimeout(id)
      }
    })
  • 相关阅读:
    import()函数
    node-sass安装报错
    npm 安装扩展模块时,因缓存报错的问题汇总
    测试
    export default 和 export 区别
    正则
    物联网
    第十二次课堂总结
    第十二次作业
    作业10
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13869738.html
Copyright © 2011-2022 走看看