前端异步解决方案-1(callback,事件监听);

2次阅读

共计 1257 个字符,预计需要花费 4 分钟才能阅读完成。

今天在学习 koa2 的时候发现自己对 async 的使用方法和原理都不是很熟悉,连带着发现自己对前端异步的解决方案并了解并不如何深刻,所以干脆把前端现有的异步解决方案都复习了一遍。今天先把将用 callback 和事件监听思想解决异步问题的代码贴出来,明天再补充代码的解析及其他解决方案;
CallBack
function f1(f2) {
setTimeout(function () {
let b = 10;
f2(b)
}, 1000)
}

function f2(data) {
console.log(“callback_type_demo”, data)
}
f1(f2);
事件监听
// 实现事件监听
let DOM = function () {
// 被监听的事件的集合
this.eventList = {};
// 绑定事件监听的方法
this.on = function (eventName, fun) {
if (typeof eventName !== “string”) {
console.error(“ 监听的事件名应为字符串 ”);
return;
}
if (typeof fun !== “function”) {
console.error(“ 被触发的必须是事件 ”);
return;
}
this.eventList[eventName] = this.eventList[eventName] || [];
this.eventList[eventName].push(fun);
};
// 移除事件监听的方法
this.removeOn = function (eventName, fun) {
let onList = this.eventList[eventName];
if (onList) {
for (let i = 0; i < onList.length; i++) {
if (onList[i] === fun) {
onList.splice(i, 1);
return
}
}
}
};
// 触发事件监听的方法
this.trigger = function (eventName, param) {
let onList = this.eventList[eventName];
if (onList) {
for (let i = 0; i < onList.length; i++) {
onList[i](param)
}
}
};
};

let dom1 = new DOM();
let dom2 = new DOM();
let f2 = function () {
setTimeout(function () {
dom1.trigger(‘done’, 20)
}, 100)
};
let f3 = function (data) {
console.log(data)
};
dom1.on(“done”, f3);
f2();
setTimeout(function () {
console.log(“removeOn”);
dom1.removeOn(“done”, f3);
f2();
}, 200);
dom1.trigger(“done”, “123”);
dom2.trigger(“done”, “123”);
由于时间关系今天不多做解析,明天再来解析我的代码和运行结果

正文完
 0