Most basic computed KO binding

Builds on "Most basic" by showing ko.computed

by ozzymcduff

HTML

<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<p>Name: <input data-bind='value: firstName' /></p> 
<p>Name: <input data-bind='value: lastName' /></p> 
<p>FullName: <strong data-bind='text: fullName()' ></strong> 
    <span data-bind="slideVisible:showDots()">(OOO)</span>

CSS

body { font-family: arial; font-size: 14px; }
p { margin: 0.9em;  }

JavaScript

// Here's my data model
var viewModel = {
    firstName: ko.observable("Sky"),
    lastName: ko.observable("King"),
};

viewModel.fullName = function() {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
    return viewModel.firstName() + " " + viewModel.lastName();
};

viewModel.showDots = function(){
    return viewModel.fullName().length>10;
};

ko.bindingHandlers.slideVisible = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        var value = valueAccessor();
        var valueUnwrapped = ko.unwrap(value);
 
        // Now manipulate the DOM element
        if (valueUnwrapped == true)
            $(element).show(); // Make the element visible
        else
            $(element).hide();   // Make the element invisible
    
    },
    update: function(element, valueAccessor, allBindings) {
        // First get the latest data that we're bound to
        var value = valueAccessor();
 
        // Next, whether or not the supplied model property is observable, get its current value
        var valueUnwrapped = ko.unwrap(value);
 
        // Grab some more data from another binding property
        var duration = allBindings.get('slideDuration') || 400; // 400ms is default duration unless otherwise specified
 
        // Now manipulate the DOM element
        if (valueUnwrapped == true)
            $(element).slideDown(duration); // Make the element visible
        else
            $(element).slideUp(duration);   // Make the element invisible
    }
};

// This makes Knockout get to work
ko.applyBindings(viewModel);