JSFiddle - React, Tailwind, and code Playground

by nicholasstephan

HTML

<script src="http://rniemeyer.github.com/KnockMeOut/Scripts/knockout-latest.debug.js"></script>
<div data-bind="if:loggedIn">
    We're logged in...
    <button data-bind="click:logOut">Log Out</button>
</div>
<div data-bind="ifnot:loggedIn">
    We're not logged in...
    <button data-bind="click:logIn">Log In</button>
</div>

JavaScript

//an observable that retrieves its value when first bound
ko.onDemandObservable = function(callback, target) {
    var _value = ko.observable();  //private observable

    var result = ko.computed({
        read: function() {
            //if it has not been loaded, execute the supplied function
            if (!result.loaded()) {
                callback.call(target);
            }
            //always return the current value
            return _value();
        },
        write: function(newValue) {
            //indicate that the value is now loaded and set it
            result.loaded(true);
            _value(newValue);
        },
        deferEvaluation: true  //do not evaluate immediately when created
    });

    //expose the current state, which can be bound against
    result.loaded = ko.observable();
    
    //load it again
    result.refresh = function() {
        result.loaded(false);
    };

    return result;
};

var VM = {
    isLoggedIn: function() {
        this.loggedIn(false);
    },
    logIn: function() {
        this.loggedIn(true);
    },
    logOut: function() {
        this.loggedIn(false);
    }
};

VM.loggedIn = ko.onDemandObservable(VM.isLoggedIn, VM),
    

VM.loggedIn.subscribe(function(val) {
    alert('logged in: ' + val);
});

ko.applyBindings(VM);