KO Bindings Shenanigans

by Jason Butz

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!--
    Remove the parenthesis from myVisible and it will always be visible
    
    Remove the parenthesis from myValueGenerator and the code of the function
    will be returned
-->
<p data-bind="text: myValueGenerator(), visible: myVisible()">
</p>

JavaScript

class App {
	constructor() {
    	this.value = ko.observable(1);
        
        setInterval(() => {
        	this.value(this.value() + 1);
        }, 2000);
    }
    
    myValueGenerator() {
    	return `#${this.value()}`;
    }
    
    myVisible() {
    	return this.value() % 2 == 0;
    }
}

ko.applyBindings(new App());