Skip to content

Instantly share code, notes, and snippets.

@axetroy axetroy/observer.js
Last active Apr 24, 2017

Embed
What would you like to do?
简单的发布订阅者模式的实现
var Observer = function () {
};
Observer.prototype = {
constructor: Observer,
subscribe: function (eventName, func) {
if (!this[eventName]) this[eventName] = [];
this[eventName].push(func);
},
publish: function (eventName, data) {
var _this = this;
if (!this[eventName]) this[eventName] = [];
this[eventName].forEach(function (func) {
func.call(_this, data);
});
}
};
@axetroy

This comment has been minimized.

Copy link
Owner Author

axetroy commented Apr 24, 2017

使用:

var ob = new Observer();
// 订阅
ob.subscribe('dialog', function (data) {
  console.log('there are data:' + data);
});
// 发布
ob.publish('dialog', [1, 2, 3, 4]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.