为了账号安全,请及时绑定邮箱和手机立即绑定

使用香草Javascript ES6的链延迟功能

使用香草Javascript ES6的链延迟功能

陪伴而非守候 2021-05-10 15:37:43
您如何像jQuery库一样实现延迟?-我知道这个问题已经问过很多次了,但是还没有人见过使用async/awaitES6样式学来实现它。让我知道你是否有想法//create a jquery like libraryclass DOM {    constructor(selector){        this.elements = [];        if(!selector){            return;        } else if(selector === 'document' || selector === 'window'){            this.elements = [selector];        } else {            this.elements = Array.from(document.querySelectorAll(selector));        }    }    on(){        console.log('on');        return this;    }    get(){        console.log('get');        return this;    }    delay(ms, callback){        //how to implement this? how to chain result of callback onto next chain?        console.log('delay');        const promise = Promise.resolve();        return promise.then(function(resolve) {            setTimeout(function(){                resolve(this);            }, ms);        });    }}const $ = function(selector) {    return new DOM(selector);}       $('document').on().delay(10000).get()
查看完整描述

2 回答

?
当年话下

TA贡献1890条经验 获得超9个赞

您可能根本不需要诺言async/await,我想您可以创建一个Proxy对象来拦截后续调用。


这个想法是,当.delay(duration)被调用时,它将返回一个代理对象而不是类实例。此代理对象将拦截方法调用,为设置超时duration,然后使用原始类实例调用该方法。


class J {

  constructor(selector) {

    this.$element = document.querySelector(selector)

  }

  delay(duration) {

    const proxy = new Proxy(this, {

      get: (target, prop) => {

        const f = target[prop]

        return (...args) => {

          setTimeout(() => {

            return f.apply(target, [...args])

          }, duration)


          // return the class instance again, so subsequent call & delay still works

          return this

        }

      }

    })

    return proxy

  }

  text(content) {

    this.$element.textContent = content

    return this

  }

}


const $ = selector => new J(selector)


$('#test').text('hello').delay(1000).text('world')

<div id="test"></div>


查看完整回答
反对 回复 2021-05-13
  • 2 回答
  • 0 关注
  • 165 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信