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

【手写代码】事件发布订阅模式 #4

Open
leeword opened this issue Mar 24, 2021 · 0 comments
Open

【手写代码】事件发布订阅模式 #4

leeword opened this issue Mar 24, 2021 · 0 comments

Comments

@leeword
Copy link
Owner

leeword commented Mar 24, 2021

class Event {
  constructor() {
    this.eventList = Object.create(null);
  }

  $on(event, fn) {
    (this.eventList[event] || (this.eventList[event] = [])).push(fn);
  }

  $off(event, fn) {
    let fns = this.eventList[event];
    if (!fns) return false;

    if (!fn) {
      fns.length = 0;
    } else {
      const fnIndex = fns.indexOf(fn);

      if (fnIndex >= 0) {
        fns.splice(fnIndex, 1);
      }
    }
  }

  $once(event, fn) {
    const onceWrapper = (...args) => {
      this.$off(event, onceWrapper);
      fn.apply(this, args);
    }

    this.$on(event, onceWrapper);
  }

  $trigger(event, ...args) {
    const fns = this.eventList[event];
    if (!fns) return false;

    fns.forEach(fn => fn.apply(this, args));
  }
}

export default Event;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant