js利用trigger和bind实现自定义事件的定义和触发

示例一:

看一组示例demo:(js实现事件模型bind与trigger

function Emitter() {
this._listener = []; //_listener[自定义的事件名] = [所用执行的匿名函数1, 所用执行的匿名函数2]
}

//注册事件
Emitter.prototype. bind = function ( eventName, callback) {
var listener = this._listener[eventName] || []; //this._listener[eventName]没有值则将listener定义为[](数组)。
listener. push(callback);
this._listener[eventName] = listener;
}

//触发事件
Emitter.prototype. trigger = function ( eventName) {
var args = Array.prototype.slice. apply( arguments). slice( 1); //atgs为获得除了eventName后面的参数(注册事件的参数)
var listener = this._listener[eventName];

if ( ! Array. isArray(listener)) return; //自定义事件名不存在
listener. forEach( function ( callback) {
try {
callback. apply( this, args);
} catch (e) {
console. error(e);
}
})
}

//实例
var emitter = new Emitter();
emitter. bind( "myevent", function ( arg1, arg2) {
console. log(arg1, arg2);
});

emitter. bind( "myevent", function ( arg1, arg2) {
console. log(arg2, arg1);
});

emitter. trigger( "myevent", "a", "b")


示例二:(js实现事件模型bind与trigger

function LazyMan( name) {
return new _LazyMan(name);
}
function _LazyMan( name) {
console. log( "Hi This is " + name)
this.task = [];
var _this = this;
var namer = ( function( name) {
return function() {
console. log(name);
_this. next();
}
})(name)
this.task. push(namer);
setTimeout( function() {
_this. next();
}, 0);
return this;
}
_LazyMan.prototype.next = function() {
var fn = this.task. shift();
fn && fn();
}
_LazyMan.prototype. eat = function( val) {
var _this = this;
var eat = ( function( val) {
return function() {
console. log( "eat" + val);
_this. next();
}
})(val);
this.task. push(eat);
return this;
}
_LazyMan.prototype. sleep = function( time) {
var _this = this;

var timer = ( function( time) {
return function() {
setTimeout( function() {
console. log( "wait");
console. log( "time=" + time);
_this. next();
}, time * 1000);
}
})(time);
this.task. push(timer);
return this;
}

//LazyMan("Hank").eat("dinner").eat("supper");
LazyMan( "Hank"). sleep( 3). eat( "dinner");


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值