var PubSub = {
subscribe: function (ev, cb) {
var calls = this._cbs || (this._cbs = {});
(this._cbs[ev] || (this._cbs[ev] = [])).push(cb);
return this;
},
publish: function () {
var args = [].slice.call(arguments, 0);
var ev = args.shift();
var list, calls, i, l;
if (!(calls = this._cbs)) return this;
if (!(list = this._cbs[ev])) return this;
for (i = 0, l = list.length; i < l; i++) {
list[i].apply(this, args);
}
return this;
}
};
PubSub.subscribe('hello', function (data) {
console.log(data);
});
PubSub.publish('hello', '你好啊,我是参数。');
基于jquery的发布/订阅(Pub/Sub)实现:
(function () {
var o = $({});
$.subscribe = function() {
o.bind.apply(o, arguments);
};
$.unsubscribe = function() {
o.unbind.apply(o, arguments);
};
$.publish = function() {
o.trigger.apply(o, arguments);
};
})(jQuery);
本文介绍了一种简单的发布/订阅(Pub/Sub)模式实现方法。通过使用纯JavaScript和jQuery两种方式来展示如何创建发布订阅系统,使得不同的组件可以解耦并响应特定事件。
21万+

被折叠的 条评论
为什么被折叠?



