javascript 自定義事件

javascript的自定義事件,仍是頗有趣的,也很靈活。
就至關於,我不知道你要幹什麼,何時幹,可是我監聽這個動做。
只要你有這個動做,OK,那麼就能夠去執行。
下面是代碼:javascript

;(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 是一次性綁定。java

實際上不難,只是開拓了腦回路。
雖然,不知道內部的事件是如何實現的,可是,這樣的自定義事件,給人很爽的感受。this

雖然,代碼不多,可是卻能實現不少的東西。
另外,實現的場景很重要。
你能夠自定義事件,也能夠去監聽他。 可是,關鍵的是何時觸發他。prototype

^-^code

相關文章
相關標籤/搜索