我发现这个地方有点茫然,但是如果我不能做到这一点:
koObserv(koObserv() + 1);
并没有提供方法,我被迫做了:
koObserv = ko.observable(koObserv() + 1)
这看起来很笨拙..还有另外一种方法我不知道吗?
答案 0 :(得分:30)
答案 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)">