[前端] until封装watch常用逻辑简化代码写法

2018 0
Honkers 2022-10-21 15:35:52 | 显示全部楼层 |阅读模式
目录

    引言1.示例2.源码
      2.1 toMatch2.2 toBe2.3 toBeTruthy、toBeNull、toBeUndefined、toBeNaN2.4 toContains2.5 changed和changedTimes2.6 until返回值——instance
    3.总结


引言

在之前的系列文章中我们介绍了vueuse对watch封装的一系列方法,以便我们可以更高效的开发。有对回调进行控制的watchWithFilter,有适用于当watch的值为真值时触发回调的whenever,还有只触发一次的watchOnce和最多触发一定次数的watchAtMost。但是我们最常用的场景可能是被观察的变量在满足某个具体条件时则触发回调,今天要学习的until就是直到满足某种条件时则触发一次回调函数。让我们通过示例代码和源码来研究一下吧~

1.示例

结合文档的介绍,笔者写了如下的demo代码:
  1. <script setup lang="ts">
  2. import { until , invoke } from '@vueuse/core'
  3. import {ref} from 'vue'
  4. const source = ref(0)
  5. invoke(async () => {
  6.   await until(source).toBe(4)
  7.   console.log('满足条件了')
  8. })
  9. const clickedFn = () => {
  10.   source.value ++
  11. }
  12. </script>
  13. <template>
  14. <div>{{source}}</div>
  15.   <button @click="clickedFn">
  16.     点击按钮
  17.   </button>
  18. </template>
复制代码
如上代码所示,规定了当source的值为4的时候触发执行watch回调函数。这里使用到了invoke方法,我们之前接触过,源码如下
  1. export function invoke<T>(fn: () => T): T {
  2.   return fn()
  3. }
复制代码
给定参数fn为一个函数,invoke返回函数的执行结果。代码运行效果如下图所示:


当点击次数达到4次时,打印了相应的信息。

2.源码

until代码较多,先看两张预览图,了解一下其大概实现:




通过以上两张图片我们看到until内部定义了很多的用于判断条件是否满足的方法,最后返回的instance也是包含这些方法的对象。下面我们对这些方法逐个分析。

2.1 toMatch
  1. function toMatch(
  2.     condition: (v: any) => boolean,
  3.     { flush = 'sync', deep = false, timeout, throwOnTimeout }: UntilToMatchOptions = {},
  4.   ): Promise<T> {
  5.     let stop: Function | null = null
  6.     const watcher = new Promise<T>((resolve) => {
  7.       stop = watch(
  8.         r,
  9.         (v) => {
  10.           if (condition(v) !== isNot) {
  11.             stop?.()
  12.             resolve(v)
  13.           }
  14.         },
  15.         {
  16.           flush,
  17.           deep,
  18.           immediate: true,
  19.         },
  20.       )
  21.     })
  22.     const promises = [watcher]
  23.     if (timeout != null) {
  24.       promises.push(
  25.         promiseTimeout(timeout, throwOnTimeout)
  26.           .then(() => unref(r))
  27.           .finally(() => stop?.()),
  28.       )
  29.     }
  30.     return Promise.race(promises)
  31.   }
复制代码
在promise构造函数的参数函数中调用watch API来监听数据源r 。当数据源r的新值代入到条件condition中,使得condition为true时则调用stop停止监听数据源,并将promise状态变为成功。
promise放入promises数组中,如果用户传了timeout选项则promises放入调用promiseTimeout返回的promise实例。最后返回的是Promise.race的结果。看一下promiseTimeout的代码:
  1. export function promiseTimeout(
  2.   ms: number,
  3.   throwOnTimeout = false,
  4.   reason = 'Timeout',
  5. ): Promise<void> {
  6.   return new Promise((resolve, reject) => {
  7.     if (throwOnTimeout)
  8.       setTimeout(() => reject(reason), ms)
  9.     else
  10.       setTimeout(resolve, ms)
  11.   })
  12. }
复制代码
promiseTimeout返回了一个promise, 如果throwOnTimeout为true则过ms毫秒之后则将promise变为失败状态,否则经过ms毫秒后调用resolve,使promise变为成功状态。

2.2 toBe
  1. function toBe<P>(value: MaybeRef<P | T>, options?: UntilToMatchOptions) {
  2.     if (!isRef(value))
  3.       return toMatch(v => v === value, options)
  4.     const { flush = 'sync', deep = false, timeout, throwOnTimeout } = options ?? {}
  5.     let stop: Function | null = null
  6.     const watcher = new Promise<T>((resolve) => {
  7.       stop = watch(
  8.         [r, value],
  9.         ([v1, v2]) => {
  10.           if (isNot !== (v1 === v2)) {
  11.             stop?.()
  12.             resolve(v1)
  13.           }
  14.         },
  15.         {
  16.           flush,
  17.           deep,
  18.           immediate: true,
  19.         },
  20.       )
  21.     })
  22.      // 和toMatch相同部分省略
  23.   }
复制代码
toBe方法体大部分和toMatch相同,只是watch回调函数不同。这里对数据源r和toBe的参数value进行监听,当r的值和value的值相同时,使promise状态为成功。注意这里的watch使用的是侦听多个源的情况。

2.3 toBeTruthy、toBeNull、toBeUndefined、toBeNaN
  1. function toBeTruthy(options?: UntilToMatchOptions) {
  2.   return toMatch(v => Boolean(v), options)
  3. }
  4. function toBeNull(options?: UntilToMatchOptions) {
  5.   return toBe<null>(null, options)
  6. }
  7. function toBeUndefined(options?: UntilToMatchOptions) {
  8.   return toBe<undefined>(undefined, options)
  9. }
  10. function toBeNaN(options?: UntilToMatchOptions) {
  11.   return toMatch(Number.isNaN, options)
  12. }
复制代码
toBeTruthy和toBeNaN是对toMatch的封装,toBeNull和toBeUndefined是对toBe的封装。toBeTruthy判断是否为真值,方法是使用Boolean构造函数后判断参数v是否为真值。
toBeNaN判断是否为NAN, 使用的是Number的isNaN作为判断条件,注意toBeNaN的实现不能使用toBe, 因为tobe在做比较的时候使用的是 ‘===’这对于NaN是不成立的:


toBeNull用于判断是否为null,toBeUndefined用于判断是否为undefined。

2.4 toContains
  1. function toContains(
  2. value: any,
  3. options?: UntilToMatchOptions,
  4. ) {
  5.   return toMatch((v) => {
  6.     const array = Array.from(v as any)
  7.     return array.includes(value) || array.includes(unref(value))
  8.   }, options)
  9. }
复制代码
判断数据源v中是否有value,Array.from把v转换为数组,然后使用includes方法判断array中是否包含value。

2.5 changed和changedTimes
  1. function changed(options?: UntilToMatchOptions) {
  2.   return changedTimes(1, options)
  3. }
  4. function changedTimes(n = 1, options?: UntilToMatchOptions) {
  5.   let count = -1 // skip the immediate check
  6.   return toMatch(() => {
  7.     count += 1
  8.     return count >= n
  9.   }, options)
  10. }
复制代码
changed用于判断是否改变,通过调用changedTimes和固定第一参数n为1实现的。changedTimes的第一个参数为监听的数据源改变的次数,也是通过调用toMatch实现的,传给toMatch的条件是一个函数,此函数会在数据源改变时调用。每调用一次外层作用域定义的count就会累加一次 ,注意外层作用域count变量声明为-1, 因为时立即监听的。
至此,until源码内定义的函数全部分析完毕,下图总结了这些函数之前的调用关系:


源码中最后的返回值也值得我们说一说。

2.6 until返回值——instance

until的返回值分为两种情况:当监听的源数据是数组时和不是数组时,代码如下图所示:
  1. if (Array.isArray(unref(r))) {
  2.   const instance: UntilArrayInstance<T> = {
  3.     toMatch,
  4.     toContains,
  5.     changed,
  6.     changedTimes,
  7.     get not() {
  8.       isNot = !isNot
  9.       return this
  10.     },
  11.   }
  12.   return instance
  13. }
  14. else {
  15.   const instance: UntilValueInstance<T, boolean> = {
  16.     toMatch,
  17.     toBe,
  18.     toBeTruthy: toBeTruthy as any,
  19.     toBeNull: toBeNull as any,
  20.     toBeNaN,
  21.     toBeUndefined: toBeUndefined as any,
  22.     changed,
  23.     changedTimes,
  24.     get not() {
  25.       isNot = !isNot
  26.       return this
  27.     },
  28.   }
  29.   return instance
  30. }
复制代码
我们看到数据源时数组时返回的方法中没有toBeTruthy,toBeNull,toBeNaN,toBeUndefined这些用于判断基本类型值的方法。另外需要注意的是返回的instance里面有一个get not(){// ...}这是使用getters, 用于获取特定的属性(这里是not)。在getter里面对isNot取反,isNot返回值为this也就是instance本身,所以读取完not属性后可以链式调用其他方法,如下所示:
  1. await until(ref).not.toBeNull()
  2. await until(ref).not.toBeTruthy()
复制代码
3.总结

until方法用于对数据监听,返回具有多个条件判断函数的对象,使用者可以将条件做为这些函数的参数,当监听的数据满足条件则停止监听,其本质是对watch的回调进行封装,并结合promise.race的一个异步方法。本文的demo代码已经上传至github, 欢迎您clone并亲自体验until的使用。
以上就是until封装watch常用逻辑简化代码写法的详细内容,更多关于until封装watch逻辑的资料请关注中国红客联盟其它相关文章!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Honkers

特级红客

关注
  • 3159
    主题
  • 36
    粉丝
  • 0
    关注
这家伙很懒,什么都没留下!

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行