Skip to content

Instantly share code, notes, and snippets.

@axetroy
Last active April 24, 2017 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save axetroy/0b024b37625cba2d0f211759afac9902 to your computer and use it in GitHub Desktop.
Save axetroy/0b024b37625cba2d0f211759afac9902 to your computer and use it in GitHub Desktop.
简单的发布订阅者模式的实现
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
Copy link
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