Yesterday I used vue to provide an event publishing subscription, so today I implemented one myself, found it is not too difficult, directly on the code:
function EventBus() {}
EventBus.prototype.on = function(name, callback) {// If there is no event object, add oneif(! This._events){// Create a clean Object with no prototype chain this._events = object.create (null); } // If there is no subscription to this event, add one, if there is, push itif(! this._events[name]){ this._events[name] = [callback]; }else{
this._events[name].push(callback);
}
}
EventBus.prototype.emit = function(name, ... Args) {// At publish time, if the event is present, the loop executes all the subscribed methodsif(this._events[name]){ this._events[name].forEach(callback => { callback(... args); }) } } EventBus.prototype.off =function(name) {// If there are subscriptions for this event, clear all subscriptionsif(this._events[name]){
delete this._events[name];
}
}
EventBus.prototype.once = function (name, callback) {
letonce = (... args) => { callback(... args); this.off(name); }; this.on(name, once); }let eventBus = new EventBus();
eventBus.on('on'.function (msg) {
console.log(msg);
})
eventBus.once('once'.function (msg) {
console.log(msg);
})
eventBus.on('off'.function (msg) {
console.log(msg);
})
eventBus.emit('on'.'release on1'// Publish on1 eventbus.emit ('on'.'release on2'// Publish on2 eventbus.emit ('once'.'release once')// Publish once eventbus.emit ('once'.'release once')
eventBus.emit('off'.'release off'// Publish off eventbus.off ('off')
eventBus.emit('off'.'release off')
Copy the code
On, off and emit have nothing to say, it is a simple publish and subscribe method, and I can understand the code by looking at it. The once method is actually executing on, and then executing off. We can use function hijacking to hijack the subscription method and still execute on. But the callback becomes its own, and when its own callback is executed, off removes the subscription, which is also known as slice programming.
EventBus.prototype.once = function (name, callback) {
letonce = (... args) => { callback(... args); this.off(name); }; this.on(name, once); }Copy the code
Yesterday, someone asked me what eventBus would look like. Honestly, I couldn’t figure it out. For example, chat click to enter a page, unread messages are mostly displayed on the same page, and then used for scenarios of different components, or different pages destroy some scenarios that will cause memory leaks. There are other solutions for everything eventBus can solve, and other solutions can also be solved by eventBus. Maybe you will feel very fragrant when you use eventBus in the future.