你怎么增加knockout.js可观察?

时间:2012-03-03 18:50:28

标签: javascript knockout.js

我发现这个地方有点茫然,但是如果我不能做到这一点:

koObserv(koObserv() + 1);

并没有提供方法,我被迫做了:

koObserv = ko.observable(koObserv() + 1)

这看起来很笨拙..还有另外一种方法我不知道吗?

3 个答案:

答案 0 :(得分:30)

这是一个演示渐增的小提琴:

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

正如您所看到的,self.num(self.num() + 1);确实有效。

答案 1 :(得分:9)

您可以将这些逻辑抽象为可扩展的可观察

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

答案 2 :(得分:3)

我建议你,如果你使用了很多增量,创建一些辅助函数来做增量并将它传递给你的observable的引用。最终会得到更易读的代码。

<强> 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