background
In business development, we often encounter the problem of dealing with cross-page communication. For example, when a user opens a website, some pages of the website need to display different data according to the user's login status. Obviously, this requires us to log in successfully at the moment,
Go to notifications to those pages that need to be changed. To solve problems like this, the publish-subscribe model was born.
ideas
A simple publish-subscribe model requires event binding and triggering to be isolated from each other, while supporting dynamic addition and deletion of events. Based on this, there is an idea:
- define a variable to store these events
- Define a listener method to add the event to the event variable
- Define a delete method to remove the event from the variable
- Define a trigger method that calls the event in the variable
accomplish
According to the above ideas, it can be roughly known that the usage is similar to the following:
var emitter = new EventEmitter();
var handle = function (data) {
console.log(data)
}
// 页面A订阅LOGIN事件
emitter.on('LOGIN', handle)
// 登录成功,触发发布
emitter.emit('LOGIN', {user: { name: 'Jan', age: 18}})
specific code implementation
function EventEmitter() {
// 事件变量
this._event = {}
}
// 添加订阅
EventEmitter.prototype.on= function (type, handle) {
this._event[type] = this._event[type] || []
this._event[type].push(handle)
}
// 移除订阅
EventEmitter.prototype.remove = function (type, handle) {
var index = (this._event[type] || []).indexOf(handle)
if(index !== -1) {
this._event[type].splice(index, 1)
}
}
// 触发发布
EventEmitter.prototype.emit = function (type, data) {
(this._event[type] || []).forEach(function (handle) {
handle(data)
})
}
How to implement a simple -
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。