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

您如何像jQuery库一样实现延迟?-我知道这个问题已经问过很多次了,但是还没有人见过使用async/awaitES6样式学来实现它。让我知道你是否有想法


//create a jquery like library

class 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()


陪伴而非守候
浏览 166回答 2
2回答

当年话下

您可能根本不需要诺言async/await,我想您可以创建一个Proxy对象来拦截后续调用。这个想法是,当.delay(duration)被调用时,它将返回一个代理对象而不是类实例。此代理对象将拦截方法调用,为设置超时duration,然后使用原始类实例调用该方法。class J {&nbsp; constructor(selector) {&nbsp; &nbsp; this.$element = document.querySelector(selector)&nbsp; }&nbsp; delay(duration) {&nbsp; &nbsp; const proxy = new Proxy(this, {&nbsp; &nbsp; &nbsp; get: (target, prop) => {&nbsp; &nbsp; &nbsp; &nbsp; const f = target[prop]&nbsp; &nbsp; &nbsp; &nbsp; return (...args) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setTimeout(() => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return f.apply(target, [...args])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, duration)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // return the class instance again, so subsequent call & delay still works&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return this&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })&nbsp; &nbsp; return proxy&nbsp; }&nbsp; text(content) {&nbsp; &nbsp; this.$element.textContent = content&nbsp; &nbsp; return this&nbsp; }}const $ = selector => new J(selector)$('#test').text('hello').delay(1000).text('world')<div id="test"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript