[英]How do you increment a knockout.js observable?
我發現這個地方有點茫然,但如果我不能這樣做:
koObserv(koObserv() + 1);
我沒有提供方法,我被迫做了:
koObserv = ko.observable(koObserv() + 1)
這看起來很笨拙..還有另外一種方法,我錯過了嗎?
你可以將這些邏輯抽象為一個可觀察的擴展
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
我建議你,如果你使用了很多增量,創建一些輔助函數來做增量並傳遞你的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)">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.