Skip to content

Instantly share code, notes, and snippets.

@hipi
Last active September 13, 2021 08:07
Show Gist options
  • Save hipi/a7db5f5d48a160b69e2089b32ef8b601 to your computer and use it in GitHub Desktop.
Save hipi/a7db5f5d48a160b69e2089b32ef8b601 to your computer and use it in GitHub Desktop.
发布订阅模式
function PubSub() {
this._event = {};
this.on = function (eventName, handler) {
if (this._event[eventName]) {
this._event[eventName].push(handler);
} else {
this._event[eventName] = [handler];
}
};
this.emit = function (eventName) {
var events = this._event[eventName];
var otherArgs = Array.prototype.slice.call(arguments).slice(1);
var self = this;
if (events) {
events.forEach(function (event) {
event.apply(self, otherArgs);
});
}
};
this.off = function (eventName, handler) {
var events = this._event[eventName];
if (events) {
this._event[eventName] = events.filter(function (event) {
return event !== handler;
});
}
};
this.once = function (eventName, handler) {
var self = this;
function func() {
var args = Array.prototype.slice.call(arguments);
handler.apply(self, args);
this.off(eventName, func);
}
this.on(eventName, func);
};
this.removeAll = function removeAll(eventName) {
delete this._event[eventName];
};
}
// ES6
class PubSub {
constructor() {
this._event = {};
}
on(eventName, handler) {
if (this._event[eventName]) {
this._event[eventName].push(handler);
} else {
this._event[eventName] = [handler];
}
}
emit(eventName) {
const events = this._event[eventName];
const otherArgs = [...arguments].slice(1);
const self = this;
if (events) {
events.forEach(event => {
event.apply(self, otherArgs);
});
}
}
off(eventName, handler) {
const events = this._event[eventName];
if (events) {
this._event[eventName] = events.filter(event => {
return event !== handler;
});
}
}
once(eventName, handler) {
const self = this;
function func() {
const args = [...arguments];
handler.apply(self, args);
this.off(eventName, func);
}
this.on(eventName, func);
}
removeAll(eventName){
delete this._event[eventName];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment