JSFiddle - React, Tailwind, and code Playground

by belorion

HTML

<div id='title' style='text-decoration: underline;'>some title</div>
<div id='state1' class='clickable'>click to set state2 (title = 'second')</div>
<div id='state2' class='clickable'>click to set state3  (title = 'third')</div>
<br/>
<div id='undo' class='clickable'>undo</div>

CSS

.clickable{
    cursor: pointer;
}

JavaScript

var StateHelper = function(){
    var stateList = [];
    var callbacks = [];

    this.onChange = function(callback){
        callbacks.push(callback);
    };

    this.set = function(opts){
        stateList.push(opts);
        apply(opts);
    };
    
    this.undo = function(){
        if(stateList.length <= 1){
            return; // nothing to undo
        }
    
        // To undo, we go back 2, since top of stack is current
        stateList.pop();
        var last = stateList[stateList.length - 1];
        apply(last);
    };
    
    var apply = function(opts){
        var length = callbacks.length;
        for(var i = 0; i < length; i++){
            callbacks[i](opts);
        }
    };
};

var updateTitle = function(opts){
    // Update the pages title based on state
    console.log('title updating');
    $('#title').text(opts.title);
};

var myState = new StateHelper();
myState.onChange(updateTitle);

var state2 = { title: 'second' };
var state3 = { title: 'third' };

$(document).ready(function(){
    $('#state1').click(function(){
        myState.set(state2);
    });
    
    $('#state2').click(function(){
        myState.set(state3);
    });
    
    $('#undo').click(function(){
        myState.undo();
    });
    
    // Set initial state
    myState.set({title: 'some title'});
});