knockout example with datastore

by Richard Hunter

HTML

<div data-bind="text: productTester().name"></div>


<ul>
    <li data-bind="click: changeTester.bind($data,'123')">green</li>
    <li data-bind="click: changeTester.bind($data,'234')">pink</li>
     <li data-bind="click: changeTester.bind($data,'456')">blue</li>
     <li data-bind="click: changeTester.bind($data,'456dfd')">doesn't exist</li>
    
</ul>

JavaScript

/*
    What should be an observable? 
    I think a rule of thumb is to identify the 
    'unit of change'. At times this will be individual 
    values, but on other times it may be a whole object
    whose internals are unlikely to change.

*/

var viewModel = {
    productTester : ko.observable({
        name : "red"
    }),   
    changeTester : function(id) {    
        changeProductTester(id); 
    }
};

var data = {
    '123' : {
        name : 'green'
    },
    '234' : {
        name : 'pink'
    },
    '456' : {
        name : 'blue'
    }
};

var dataService = {
    getProductTester : function(colorId) {
        return new Promise(function(resolve, reject) {
            setTimeout(function () {
                
                var d = data[colorId];
                d = d ? d : {};
                resolve(d);       
            }, 100);
        });
    }
};

function changeProductTester(colorId) {
    dataService.getProductTester(colorId).then(viewModel.productTester);
}
ko.applyBindings(viewModel);