为什么出现bug:Uncaught ReferenceError: effect is not defined

628 篇文章 6 订阅
本文探讨了如何使用JavaScript的Proxy和自定义scheduler函数实现异步副作用管理。通过实例展示了如何创建一个proxy对象并结合effect函数来监控和调度对象属性的变化,同时利用Promise和jobQueue来处理微任务。
摘要由CSDN通过智能技术生成
<!DOCTYPE html>
<html>
    <head>
        <title>document.write() Example</title>
    </head>
    <body>
        <script type="text/javascript">       
 const jobQueue = new Set()
 const p = Promise.resolve()
 let isFlushing = false
 function flushJob() {
     if (isFlushing) return
     isFlushing = true
p.then(() => {
    jobQueue.forEach(job =>job())
}).finally(() => {
    isFlushing = false
})
 }

 const data = { foo: 1 }
            const obj = new Proxy(data, {})

 effect(() => {
     console.log(obj.foo)
 }, {
     scheduler(fn) {
         jobQueue.add(fn)
         flushJob()
     }
 })
 obj.foo++
 obj.foo++
             </script> 
    </body>

</html>

还是不行

<!DOCTYPE html>
<html>
    <head>
        <title>document.write() Example</title>
    </head>
    <body>
        <script type="text/javascript">       
 //定义一个任务队列
const jobQueue = new Set()
//创建一个promise实例,将一个任务添加到微任务队列
const p = Promise.resolve()
//是否正在刷新队列
let  isFlushing = false
function flushJob(){
  //如果队列正在刷新,什么也不做
  if(isFlushing) return
  //将状态设置为true
  isFlushing = true
  //在微任务队列中刷新jobQueue队列
  p.then(() =>{
    jobQueue.forEach(job => job())
  }).finally(() =>{
    //结束后将iFlushing重置
    isFlushing = false
  })
}
 
effect(() =>{
  console.log(job.foo)
},{
  scheduler(fn){
    //将副作用函数添加到jobQueue队列
    jobQueue.add(fn)
    flushJob()
  }
})
 
job.foo++
job.foo++
             </script> 
    </body>

</html>

连这个很简单的也不行了,同样的bug
应该引用什么js?

<!DOCTYPE html>
<html>
    <head>
        <title>document.write() Example</title>
    </head>
    <body>
        <script type="text/javascript">       

const data = {foo : 1}
const obj = new Proxy(data,{
  /*.....*/})
 
effect(() => {
  console.log(obj.foo)
})
 
obj.foo++

 

             </script> 
    </body>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值