How do you increment a knockout.js observable?

后端 未结 3 992
情深已故
情深已故 2021-02-07 04:56

I\'m finding this a strange place to be at a bit of a loss, but if I cant\' do this:

koObserv(koObserv() + 1);

and a method is not provided, am

相关标签:
3条回答
  • 2021-02-07 05:25

    I would suggest you to, if you use a lot of increment, create some helper function to do the increment and pass it the reference of your observable. You end up with more readable code.

    JS:

    var increment = function (observable) {
        observable(observable() + 1);
    };
    
    var MyViewModel = function () {
        this.num1 = ko.observable(0);
    
        this.incrementNum = function (observable) {
            // passing the observable by reference to the helper function
            increment(observable);
        }
    }
    

    HTML:

    <button data-bind="click: incrementNum.bind($root, num1)">
    

    JSFiddle example

    0 讨论(0)
  • 2021-02-07 05:33

    you could abstract these logic into an extend observable

    ko.observable.fn.increment = function (value) {
        this(this() + (value || 1));
    };
    
    var counter = ko.observable(0);
    console.log(counter()); // 0
    
    counter.increment();
    console.log(counter()); // 1
    
    counter.increment();
    console.log(counter()); // 2
    
    counter.increment(5);
    console.log(counter()); // 7
    
    0 讨论(0)
  • 2021-02-07 05:41

    Here is a fiddle that demonstrates incrementing:

    http://jsfiddle.net/jearles/LbPDK/

    As you can see self.num(self.num() + 1); does work.

    0 讨论(0)
提交回复
热议问题