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

发布订阅模式 #66

Open
Liqiuyue9597 opened this issue Sep 28, 2020 · 1 comment
Open

发布订阅模式 #66

Liqiuyue9597 opened this issue Sep 28, 2020 · 1 comment

Comments

@Liqiuyue9597
Copy link
Owner

Liqiuyue9597 commented Sep 28, 2020

class Event{
  on(event, callback){
    
  }
  off(event){

  }
  emit(event, ...args){

  }
}
如果考得难的话还会有once方法等等
@Liqiuyue9597
Copy link
Owner Author

Liqiuyue9597 commented Sep 28, 2020

最开始面试官只是给了我上面框架就开始让我写,看到这道题我是懵的,因为我对发布订阅完全不熟悉。
所以我就问他能不能仔细讲解一下on、off和emit要实现什么功能,然后面试官就给我示范了一下每个方法的作用,然后就写出来了。
其实这道题本身不难,就是存任务然后想执行任务的时候全部执行就行了。但是挂上发布订阅的名字就感觉挺难的。
所以大家遇到不懂的大胆问就行了,一般面试官都会解释,如果遇到不解释的投诉他就行了。

class Event {
  constructor() {
    this.ele = {};
  }
  on(event, callback) {
    if (this.ele[event]) {
      this.ele[event].push(callback);
    } else {
      this.ele[event] = [callback];
    }
  }
  off(event) {
    if (this.ele[event]) {
      this.ele[event].filter(item => {
        return item !== event;
      });
    }
  }
  emit(event, ...args) {
    if (this.ele[event]) {
      this.ele[event].forEach(fn => {
        fn.apply(this, args);
      });
    }
  }
}

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