Knockout ViewModel Computed Observable example

by agat

HTML

Title: <input data-bind="value: title, valueUpdate: 'afterkeydown'" /><br>
Author: <input data-bind="value: author, valueUpdate: 'afterkeydown'" /><br>
Price: <input data-bind="value: price, valueUpdate: 'afterkeydown'" /><br>
Discount: <input data-bind="value: discount, valueUpdate: 'afterkeydown'" /><br>
<hr>
<h2>
    <!-- ko text: title --><!-- /ko -->
    <small data-bind="text: '(by ' + author() + ')'"></small>
</h2>
<p>Price: $<!-- ko text: priceWithDiscount --><!-- /ko --></p>

JavaScript

Workshop = function () {
    var _this = this;
    
    _this.id = 104;
    _this.title = ko.observable('Vehicle Design: Sci-Fi Ship');
    _this.author = ko.observable('Paul Christopher');
    
    _this.price = ko.observable(39.99);
    _this.discount = ko.observable(10);
    _this.priceWithDiscount = ko.computed(function () {
        return this.price() - this.price() * (this.discount() / 100)
    }, _this);
};

ko.applyBindings(new Workshop);