JSFiddle - React, Tailwind, and code Playground

by fatmatto

JavaScript

var Observable = function() {
    this.eventHandlers = [];
    this.emit = function(eventName,eventObject) {

            if (this.eventHandlers.hasOwnProperty(eventName)) {
                    this.eventHandlers[eventName].call(this,eventObject);
            }
                
        }

        this.on = function(eventName,callback) { 
            if ('function' !== typeof callback)
                throw new Error('callback must be a function');
            this.eventHandlers[eventName] = callback;
        }

        this.set = function(prop,value) {
            var oldval = this[prop];
            this[prop] = value;
            if(oldval !== this[prop])
                this.emit('change '+prop,{oldValue : oldval, newValue : value});
            
        }
}

var Observer = function() {
    
    this.observe = function(eventType,observableObject,callback) {
        observableObject.on(eventType,callback);
    }

}


var hero = new Observable();
hero.name = 'Deadpool';
hero.power = 'Katanas';
var o = new Observer();
o.observe('change name',hero,function(eventOptions){
    document.write('<p>The name of the hero changed to '+eventOptions.newValue+'</p>');
});
o.observe('change power',hero,function(eventOptions){
    document.write('<p>The power of the hero changed to '+eventOptions.newValue+'</p>');
});
hero.set('name','Wade Wilson');
hero.set('power','Regeneration');