-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
手写题:事件总线 #10
Labels
Comments
使用 const arr = [1, 2, 3, 4]
// 假设有一个 for 循环
arr.splice(i, 1) // i = 0, 此时 arr = [2, 3, 4]
arr.splice(i, 1) // i = 1, 此时 arr = [2, 4]
... |
mini 版来了 class EventEmitter {
constructor() {
this.subs = Object.create(null);
}
$on(eventType, handler) {
this.subs[eventType] = this.subs[eventType] || [];
this.subs[eventType].push(handler);
}
$emit(eventType, ...params) {
this.subs[eventType].forEach((handler) => handler(...params));
}
}
const em = new EventEmitter();
function handleClick(params1) {
console.log("clicked", params1);
}
em.$on("click", handleClick);
em.$on("click", (params1) => {
console.log("clicked2", params1);
});
em.$on("change", (params1, params2) => {
console.log(`changed:通过${params1},改变成${params2}`);
}); |
简单版 EventBus
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: