Skip to content

Instantly share code, notes, and snippets.

@benqus
Last active August 29, 2015 14:09
Show Gist options
  • Save benqus/205a2305850bedae9a43 to your computer and use it in GitHub Desktop.
Save benqus/205a2305850bedae9a43 to your computer and use it in GitHub Desktop.
Observable - Pub/Sub
/**
* Class inheritance helper
* @param {function} Class - sub class
* @param {function} Super - super class
*/
function extend(Class, Super) {
if (typeof Class !== 'function' && typeof Super !== 'function') {
return;
}
Class.prototype = Object.create(Super.prototype);
Class.prototype.constructor = Class;
};
/**
* Provides basic Pub/Sub interface and functionality
*
* @class Observable
*/
function Observable() {
this.subscribers = [];
}
/**
* Publishes the provided arguments to the subscribers.
*/
Observable.prototype.publish = function () {
var args = Array.prototype.slice.call(arguments);
this.subscribers.forEach(function (subscriber) {
subscriber.onChange.apply(subscriber, args);
});
};
/**
* Ensures that the subscriber will be notified when publishing.
* @param {object} subscriber
* @property {function} subscriber.onChange - callback to be executed when publishing
*/
Observable.prototype.subscribe = function (subscriber) {
var index = this.subscribers.indexOf(subscriber);
if (index === -1 && typeof subscriber.onChange === 'function') {
this.subscribers.push(subscriber);
}
};
Observable.prototype.unsubscribe = function (subscriber) {
var index = this.subscribers.indexOf(subscriber);
if (index > -1) {
this.subscribers.splice(index, 1);
}
};
/**
* Stores a value and provides Pub/Sub features for value changes.
*
* @class Property
* @extends {Observable}
*
* @param {*} value - initial value
*/
function Property(value) {
Observable.apply(this, arguments);
this.value = value;
}
extend(Property, Observable);
Property.prototype.get = function () {
return this.value;
};
Property.prototype.set = function (value) {
this.value = value;
this.publish(this);
};
/**
* Base Subscriber class to provide a noop Subscriber#onChange method
*/
function Subscriber() {}
Subscriber.prototype.onChange = function () {};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment