Subscribable class

Add subscribable system to any object

by Danny Michaelis

JavaScript

"use strict";

class Subscribable {
	constructor (value) {
  	this._value = value;
    this.subscriptions =  [];
  } 
  get value() {
  	return this._value
  }
  set value(newValue) {
  	const oldValue = this._value;
  	this._value = newValue;
    for(const subscription of this.subscriptions) {
    	subscription(newValue, oldValue);
    }
  }
	subscribe (subscription) {
  	this.subscriptions.push(subscription)
  }
}

const number = new Subscribable(1);
number.subscribe((newVal, old) => console.log(newVal > old))
number.subscribe((newVal, old) => console.log(newVal < old))
number.value = 2