Wei Ma
Wei Ma

Reputation: 3155

knockoutjs value binding with restriction

I am using knockoutjs to implement a shopping cart. One of the requirements is to allow customers to change quantity of item. So I naturally did

<input type="text" data-bind="value: quantity"/>

in my view mode I have an Item ViewModel defined as

Item = function(){
    ...
    _self.quantity = ko.observable(1);
    ...
}

But then there is another requirement that the total dollar amount in the shopping cart should have an upper limit.

I can use jquery to intercept the "change" event and add some logic there, but I am wondering if there is any native knockout way to do something like

<input type="text" data-bind="value: quantity where quantity*uniprice <= maxDollarAmount"/>

Upvotes: 2

Views: 79

Answers (2)

alexmac
alexmac

Reputation: 19607

You should use computed knockout observables:

ViewModel:

Item = function(){
    ...
    _self.quantity = ko.observable(1);
    _self.attemptedQuantity = ko.computed({
        read: function () {
            return _self.quantity();
        },
        write: function (value) {
            if (value * uniprice <= maxDollarAmount) {
                self.quantity(value);
            } else {
                // alert or something
            }
        }
    });
    ...
}   

Html:

<input type="text" data-bind="value: attemptedQuantity"/>

Upvotes: 4

TGH
TGH

Reputation: 39248

Use a computed observable instead. It let's you write logic to handle the value you bind to.

http://knockoutjs.com/documentation/computedObservables.html

Upvotes: 2

Related Questions