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

【前端成长之路】实现Emitter #4

Open
AmamiyaCx opened this issue Sep 3, 2022 · 0 comments
Open

【前端成长之路】实现Emitter #4

AmamiyaCx opened this issue Sep 3, 2022 · 0 comments

Comments

@AmamiyaCx
Copy link
Owner

class Emitter {
    constructor() {
        this.emitter = {};
    }

    // 触发事件,传入参数
    emit(name, ...args) {
        const callbacks = this.emitter[name];
        if (callbacks) {
            callbacks.forEach(callback => {
                callback.apply(this, args);
            });
        }
    }

    // 监听事件,执行回调
    on(name, cb) {
        const callbacks = this.emitter[name];
        if (callbacks) {
            this.emitter[name].push(cb);
        } else {
            this.emitter[name] = [cb];
        }
    }

    // 卸载事件
    off(name, cb) {
        const callbacks = this.emitter[name];
        if (callbacks) {
            let index = callbacks.findIndex(item => item === cb);
            this.emitter[name].splice(index, 1);
        }
    }

    // 只执行一次,然后删除
    once(name, cb) {
        const fn = (...args) => {
            cb.apply(this, args);
            this.off(name, fn);
        }
        this.on(fn, cb);
    }
}
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