简单事件模型,JS防止单个函数异步重复调用
function Emitter(){ this._listener = []; } Emitter.prototype.bind = function(eventName, callback){ let listener = this._listener[eventName] || []; listener.push(callback); this._listener[eventName] = listener; } Emitter.prototype.trigger = function(eventName){ //args为了获取eventName后面的参数(注册事件的参数) let args = Array.prototype.slice.apply(arguments).slice(1); let listener = this._listener[eventName]; if (!Array.isArray(listener)) { return; } listener.forEach(function(callback){ try{ callback.apply(this, args); }catch(e){ console.error(e); } }); } let emitter = new Emitter(); emitter.bind("myEvent", function(arg1, arg2){ console.log(arg1, arg2); }); emitter.bind("myevent", function(arg1, arg2){ console.log(arg1, arg2); }); emitter.trigger("myevent", "a", "b");
var status = "ready"; var doSomething = function (callback) { emitter.bind("selected", callback); console.log("add a listener!"); if (status === "ready") { status = "pending"; setTimeout(function () { emitter.trigger("selected"); status = "ready"; console.log("resolved"); }, 1000); }; }; //模拟并发请求 for (var i = 0; i < 20; i++) { setTimeout(function (i) { return (function (i) { doSomething(function () { console.log(i) }); })(i) }, 100 * i, i); };