var ev = { /** * 事件监听 * @param type 事件名称 * @param callback 事件处理函数 */ $on: function(type, callback){ if(!this.listeners){ this.listeners = {}; } if(this.fires && this.fires[type] && this.fires[type] instanceof Array && this.fires[type].length > 0){ this.fires[type].forEach(function(value){ callback.apply(this, value); }.bind(this)) if(type.indexOf('_once_') > -1){ this.fires[type] = null; } }else{ if(!this.listeners[type]){ this.listeners[type] = []; } this.listeners[type].push(callback); } }, /** * 事件解绑 * @param type 事件名字 */ $off: function(type){ if(this.listeners && this.listeners[type]){ this.listeners[type] = null; } }, /** * 一次性事件监听和触发 * @param [first] 事件名字 * @param [second] 事件处理函数 或 事件处理函数的入参 */ $once: function(/* [first] [second]*/){ var args = [].slice.call(arguments), type = [].shift.call(arguments), params = [].slice.call(arguments); if(params && (params[0] instanceof Function)){ type = '_once_' + type; this.$on(type, params[0]); }else{ args[0] = '_once_' + args[0]; this.$emit.apply(this, args); } }, /** * 触发事件 * @param [first] 事件名字 * @param [second] 事件处理函数的入参 */ $emit: function(/* [first] [second]*/){ var type = Array.prototype.shift.call(arguments), args = Array.prototype.slice.call(arguments); if(!this.fires){ this.fires = {}; } if(this.listeners && this.listeners[type] && this.listeners[type] instanceof Array && this.listeners[type].length > 0){ this.listeners[type].forEach(function(value){ value.apply(this, args); }.bind(this)) if(type.indexOf('_once_') > -1){ this.listeners[type] = null; } }else{ if(!this.fires[type]){ this.fires[type] = []; } this.fires[type].push(args); } } } ev.$on('one', function(d, s){ console.log(d + '///' + s); }) ev.$emit('two', 6, 7); setTimeout(function(){ ev.$emit('one', 3, 5); ev.$on('two', function(e, f){ console.log(e + '///' + f); }) ev.$once('three', function(){ console.log('three'); }) console.log(ev.listeners); console.log(ev.fires); }, 3000)
评论 (1 )
最新评论
p/