EventFlow.helper.js 事件流程控制

/*!
 * 事件流程管理
 * version: 1.0.0-2018.07.25
 * Requires ES6
 * Copyright (c) 2018 Tiac
 * http://www.cnblogs.com/tujia/p/9369027.html
*/

class EventFlow
{
    static init()
    {
        this.objs         = [];
        this.events       = {};
        this.currentEvent = '';
        this.currentExp   = '';
    }

    static add(selector)
    {
        this.objs.push( document.querySelectorAll(selector) );
        return this;
    }

    static on(evt)
    {
        this.events[evt]  = [];
        this.currentEvent = evt;
        return this;
    }

    static when(exp)
    {
        this.currentExp = exp;
        return this;
    }

    static then(func)
    {
        this.events[this.currentEvent].push({
            'exp': this.currentExp,
            'func': func.toString().replace(/[^\{]+\{([\s\S]+)\}$/, '$1')
        });

        this.currentExp = '';
        return this;
    }

    static run()
    {
        if(this.objs.length>0)
        {
            let i = 0;
            for(let evt in this.events){
                let commands = '';
                let events   = this.events[evt];
                for(let i in events){
                    if(events[i]['exp']!=''){
                        commands += `if(${events[i]['exp']}){
                            ${events[i]['func']}
                        }`;
                    }else{
                        commands += events[i]['func'];
                    }
                }

                this.objs[i].forEach((item, i)=>{
                    item.addEventListener(evt, function(){
                        eval(commands);
                    });
                });

                i++;
            }
        }

        this.init();
    }
}

export default EventFlow;

执行效率并不高,当写来玩呗~

import EventFlow from './EventFlow.helper.js';

EventFlow.init();

EventFlow.add('.sel-type').on('change')
.when('this.value==1').then(function(){
    // code
})
.when('this.value==2').then(function(){
    // code
})
.when('this.value==3').then(function(){
    // code
})
.when('this.value==4').then(function(){
    // code
});

EventFlow.add('.inp-name').on('input')
.then(function(){
    // code
});

EventFlow.add('.inp-name').on('blur')
.then(function(){
    // code
});

EventFlow.run();

猜你喜欢

转载自www.cnblogs.com/tujia/p/9369027.html