Skip to content

Instantly share code, notes, and snippets.

@sundarj
Last active August 29, 2015 14:27
Show Gist options
  • Save sundarj/43deaf5f1f8c67659f91 to your computer and use it in GitHub Desktop.
Save sundarj/43deaf5f1f8c67659f91 to your computer and use it in GitHub Desktop.
pub-sub pattern implemented with Harmony Proxies.
//const Proxy = require('harmony-proxy');
function Publisher() {
this.subscribers = [];
var self = this;
this.public = new Proxy({}, {
get: function (target, name) {
return target[name];
},
set: function (target, name, value) {
target[name] = value;
self.publish(target);
}
});
}
Publisher.prototype.subscribe = function (subscriber) {
this.subscribers.push(subscriber);
}
Publisher.prototype.publish = function (change) {
this.subscribers.forEach(function (subscriber) {
subscriber.notify(change);
});
}
function Subscriber(publisher) {
console.assert(publisher instanceof Publisher, "Subscribers can only be subscribed to a Publisher");
this.listeners = [];
publisher.subscribe(this);
}
Subscriber.prototype.notify = function (change) {
this.listeners.forEach(function (listener) {
listener.call(this, change);
}, this);
}
Subscriber.prototype.notified = function (listener) {
this.listeners.push(listener);
}
const moon = new Publisher;
const tide = new Subscriber(moon);
tide.notified(function (moon) {
console.log(moon.type);
});
moon.public.type = 'full';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment