Simulated Realtime Update Handling

by Jason Butz

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<input type="text" data-bind="value: inputValue, hasFocus: isEditing" style="width: 100%;" />

<button data-bind="click: start">Start Updates</button>
<button data-bind="click: stop">Stop Updates</button>

JavaScript

class App {
	constructor() {
    	this.inputValue = ko.observable('Starting value');
        this.isEditing = ko.observable(false);
        this.doRealtimeUpdate = this.doRealtimeUpdate.bind(this);
        
        this.isEditing.subscribe((newValue) => {
        	if(newValue === false && this._realtimeValue) {
            	alert(`You have an update from Realtime that you need to deal with!\n"${this._realtimeValue}"`);
            }
        })
        
        
    }
    
    start() {
    	this._interval = setInterval(() => {
        	this.doRealtimeUpdate(`Current time is ${new Date().toString()}`);
        }, 2000);
    }
    
    stop() {
		clearInterval(this._interval);
    }
    
	doRealtimeUpdate(newInputValue) {
    	if(this.isEditing()) {
        	this._realtimeValue = newInputValue;
        } else {
            this._realtimeValue = null;
        	this.inputValue(newInputValue);
        }
    }
}

ko.applyBindings(new App());