Created
September 4, 2015 17:08
-
-
Save xwartz/a7316d843f093b0041dd to your computer and use it in GitHub Desktop.
发布订阅模式
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var PubSub = { | |
// 订阅函数 | |
subscribe: function (event, callback) { | |
// 创建事件存储对象 | |
this._events = this._events || {} | |
// 添加回调函数 | |
this._events[event] = this._events[event] || [] | |
this._events[event].push(callback) | |
// 链式调用 | |
return this | |
}, | |
publish: function () { | |
// 将 arguments 转为数组 | |
var args = Array.prototype.slice.call(arguments) | |
// 提取事件 | |
var event = args.shift() | |
// 检测事件是否存在,若不存在,不做任何事 | |
if(!this._events || !this._events[event]) | |
return this | |
// 触发事件回调函数 | |
var callbacks = this._events[event] | |
callbacks.forEach(function (cb) { | |
cb.apply(this, args) | |
}, this) | |
return this | |
} | |
} | |
/** | |
* PubSub.subscribe('test', function(o){o.name}) | |
* PubSub.publish('test', {name: 'xwartz'}) | |
* / |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment