Skip to content
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

设计模式 #18

Open
jc-wow opened this issue Mar 15, 2021 · 0 comments
Open

设计模式 #18

jc-wow opened this issue Mar 15, 2021 · 0 comments

Comments

@jc-wow
Copy link
Owner

jc-wow commented Mar 15, 2021

1.订阅发布

class Event {
  constructor() {
    this.handlers = {};  // 事件中心
  }

 // 添加事件句柄
  addEventListener(type, handler) {
    if (!(type in this.handlers)) {
      this.handlers[type] = [];
    }
    this.handlers[type].push(handler);
  }

 // 分发事件句柄
  dispatchEvent(type) {
    if (!(type in this.handlers)) {
      return new Error("not descibe this event!");
    }
    const args = Array.from(arguments).slice(1);
    this.handlers[type].forEach(handler => handler(...args));
  }

// 移除事件或者移除事件句柄
  removeEvent(type, handler) {
    if (!(type in this.handlers)) {
      return new Error("not descibe this event!");
    }

    // 如果没有传入事件直接移除该订阅
    if (!handler) delete this.handlers[type];
    else {
      this.handlers[type].splice(handler, 1);
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant