js事件模型bind、unbind、trigger实现

function Emitter(){
    this._listener = {}
}
Emitter.prototype.bind = function(eventName,callback){
    var event = this._listener[eventName] || [];
    event.push(callback);
    this._listener[eventName] = event;
}
Emitter.prototype.trigger = function(eventName){
    if(!this._listener.hasOwnProperty(eventName)){
       console.log('you do not bind this event');
       return;
    }
    var args = Array.prototype.slice.apply(arguments).slice(1);
    var event = this._listener[eventName];
    if(!Array.isArray(event)) return;

    event.forEach(function(callback){
        try{
            callback.apply(this,args)
        }catch(e){
            console.log(error(e))
        }
    })
}
Emitter.prototype.unbind = function(eventName,callback){
    this._listener.hasOwnProperty(eventName) && delete this._listener[eventName];
    callback && callback();
}
var em = new Emitter();
em.bind('test',function(a,b){
    console.log(a);
    console.log(b);
});
em.trigger('test',1,2)
em.unbind('test',function(){console.log('unbind')})
em.trigger('test',1,2)

欢迎分享本文,转载请保留出处:前端ABC » js事件模型bind、unbind、trigger实现

赞 (1)
分享到:更多 ()

发表评论 0