• when
    • when-promise

    when

    egghead.io 第9课: 自定义反应
    在 egghead.io 上观看

    when(predicate: () => boolean, effect?: () => void, options?)

    when 观察并运行给定的 predicate,直到返回true。一旦返回 true,给定的 effect 就会被执行,然后 autorunner(自动运行程序) 会被清理。该函数返回一个清理器以提前取消自动运行程序。

    对于以响应式方式来进行处理或者取消,此函数非常有用。示例:

    1. class MyResource {
    2. constructor() {
    3. when(
    4. // 一旦...
    5. () => !this.isVisible,
    6. // ... 然后
    7. () => this.dispose()
    8. );
    9. }
    10. @computed get isVisible() {
    11. // 标识此项是否可见
    12. }
    13. dispose() {
    14. // 清理
    15. }
    16. }

    when-promise

    如果没提供 effect 函数,when 会返回一个 Promise 。它与 async / await 可以完美结合。

    1. async function() {
    2. await when(() => that.isVisible)
    3. // 等等..
    4. }