javascript 自定义事宜

javascript的自定义事宜,照样很风趣的,也很天真。
就相当于,我不知道你要干什么,什么时刻干,然则我监听这个行动。
只需你有这个行动,OK,那末就能够去实行。
下面是代码:

;(function(window){
    function Liu(){
        this.arr = {};
    }
    Liu.fn = Liu.prototype;
    Liu.fn.on = function(type,fn){
        if(!this.arr[type])  this.arr[type] = [];
        this.arr[type].push(fn);
    };
    Liu.fn.fire = function(event){
        if(!event.target)  event.target = this;
        if( this.arr[event.type] instanceof Array){
            for(let i=0,len=this.arr[event.type].length;i<len;i++){
                this.arr[event.type][i](event);
            }
        }
    };
    Liu.fn.off = function(type,fn){
        if(this.arr[type] instanceof Array){
            for(let i=0,len=this.arr[type].length;i<len;i++){
                if(this.arr[type][i]==fn){
                    this.arr[type].splice(i,1);
                    return true;
                }
            }
        }else{
            return false;
        }
    };
    Liu.fn.once = function(type,fn){
        var self = this;
        var fn1 = fn;
        fn = function(event){
            fn1(event);
            self.off(type,fn);
        }
        self.on(type,fn);
    };
    window.liu = new Liu();

})(window);

个中,on 是事宜监听,也能够说是增加事宜。
fire是触发事宜。
off是消除事宜与事宜处置惩罚顺序的绑定。
once 是一次性绑定。

实际上不难,只是开辟了脑回路。
虽然,不知道内部的事宜是怎样完成的,然则,如许的自定义事宜,给人很爽的觉得。

虽然,代码很少,然则却能完成许多的东西。
别的,完成的场景很主要。
你能够自定义事宜,也能够去监听他。 然则,症结的是什么时刻触发他。

^-^

    原文作者:roytime
    原文地址: https://segmentfault.com/a/1190000010391239
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞