Knockoutjs show/hide

by petermorlion

HTML

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<body>
    <div>
         <select data-bind="value: selectedValue, selectedCarType: selectedType" onchange="return false;">
             <option value="1" data-carType="Car">Car 1</option>
             <option value="2" data-carType="Car">Car 2</option>
             <option value="3" data-carType="Truck">Truck</option>
        </select>
        <div data-bind="visible: !isTruck()">
            Hide if a truck was selected.
        </div>
        <div>
            Selected type: <span data-bind="text: selectedType" />
        </div>
        <div>
            Selected value: <span data-bind="text: selectedValue" />
        </div>
        <div>
            <span href="" data-bind="click: setToCarOne">Car one</span>
            <span href="" data-bind="click: setToCarTwo">Car two</span>
            <span href="" data-bind="click: setToTruck">Truck</span>
        </div>
    </div>
</body>

JavaScript

var VehiclesViewModel = function() {
    this.selectedValue = ko.observable();
    this.selectedType = ko.observable();
    this.isTruck = ko.computed(function() {
        return this.selectedType() === 'Truck';
    }, this);
    this.setToCarOne = function() {
        this.selectedValue("1");
    };
    this.setToCarTwo = function() {
        this.selectedValue("2");
    };
    this.setToTruck = function() {
        this.selectedValue("3");
    };
}

ko.bindingHandlers.selectedCarType = {
    init: function(element, valueAccessor) {
        console.log('init');
        var value = valueAccessor();
        value($('option:selected', element).data('cartype'));

        $(element).change(function() {
            value($('option:selected', this).data('cartype'));
        });
    },
    update: function(element, valueAccessor) {
        console.log('update');
        var value = ko.utils.unwrapObservable(valueAccessor());
        $('option', element).filter(function(el) { return $(el).data('cartype') === value; }).prop('selected', 'selected');
    }
};

ko.applyBindings(new VehiclesViewModel());