KO template example

by origineil

HTML

<script type="text/html" id="label-template">
    <label class = 'otherCssStyle' data-bind="css: obs.cssStyling , text: labelValue"></label>
    <input type='text' data-bind='value: obs, valueUpdate: "afterkeydown"'></input>
</script>
 
Empty fields flag as <label class='notdone'>notdone</label>. Providing input will change it to <label class='done'>done</label></p>

<div data-bind="template: { name: 'label-template', data: {obs: someObservable, labelValue: 'First Name'}}">
</div>
 

<br/>
<br/>

<div data-bind="template: { name: 'label-template', data: {obs: someOtherObservable, labelValue: 'Last Name'}}"></div>

CSS

.notdone{
    border: solid 5px red
}

.done {
    border: solid 5px green
}

.otherCssStyle{
background: aqua
}
}

JavaScript

var specialObs = function(){
var obs = ko.observable();
    
    //just a dummy value for illustration purposes
    obs.isModified = ko.observable(true);
    
    //actual property to drive the UI
    obs.isValid = ko.computed(function(){
    return   obs() && !obs().trim() == "";
    });
    
    //Conditional styling
    obs.cssStyling = ko.computed(function() {
        return obs.isModified() && !obs.isValid() ? "notdone" : "done";
    });
    
    return obs;
}

var vm = {
    someObservable : new specialObs(), 
    someOtherObservable : new specialObs(),
}

ko.applyBindings(vm)