2018-03-07 18:20:23   Visit  94

JS事件类及继承

Lee = window.Lee||{};

Lee.Events =  function(){
    this.ets = this.ets||{};
    console.log(\\\\\\\"init Events\\\\\\\");
};
Lee.Events.prototype.on = function(name, fun){
    this.ets = this.ets||{};
    if(typeof(name)==\\\\\\\"string\\\\\\\"){
        this.ets[name] = this.ets[name]||[];
        this.ets[name].push(fun);
        fun.eventonce = false;
    }
    else{
        for(var id in name){
            this.on(id, name[id]);
        } 
    }
    return this;
};

Lee.Events.prototype.bind = Lee.Events.prototype.on;

Lee.Events.prototype.once = function(name, fun){
    this.ets = this.ets||{};
    if(typeof(name)==\\\\\\\"string\\\\\\\"){
        this.ets[name] = this.ets[name]||[];
        this.ets[name].push(fun);
        fun.eventonce = true;
    }
    else{
        for(var id in name){
            this.on(id, name[id]);
        } 
    }
    return this;
};

Lee.Events.prototype.off = function(name, fun){
    this.ets = this.ets||{};
    if(!name){
        this.ets = {};
    }
    else if(!fun){
        this.ets[name] = [];
    }
    else{
        var funs = this.ets[name];
        if(funs){
            for(var i =0;i<funs.length;i++){
                if(funs[i] == fun){
                    this.ets[name] = funs.splice(i, 1);
                    break;
                }
            }
        }
    }
    return this;
}
Lee.Events.prototype.unbind = Lee.Events.prototype.off;

Lee.Events.prototype.fire = function(name, data, propagate){
    this.ets = this.ets||{};
    if(name&&this.ets[name]){
        var funs = [];
        for(var i=0;i<this.ets[name].length; i++){
            var fun = this.ets[name][i]; 
            fun.apply(this, [data]);
            if(!fun.eventonce){
                funs.push(fun);
            }
        }
        this.ets[name] = funs;
    }
    return this;
}
//继承
Lee.ExtentClass = function(A, B){
    var Super = function(){};
    Super.prototype = B.prototype;
    var s = new Super();
    for(var id in s){
        A.prototype[id] = s[id];
    }
    //A.prototype = s;
    A.constructor = A;
    A.prototype.super = function(){
        Super.prototype.constructor.apply(this);
    }
    return A;
}

Lee.ClassTest = function(){
    
}
Lee.ExtentClass(Lee.ClassTest, Lee.Events);
Lee.ClassTest.prototype.say = function(){
    alert(\\\\\\\"hi\\\\\\\")
}
©2017 Leechg.com