javascript 你如何增加一个knockout.js observable?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9548859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:02:11  来源:igfitidea点击:

How do you increment a knockout.js observable?

javascriptknockout.js

提问by Jeremy Smith

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 I forced to do:

并且没有提供方法,我是否被迫这样做:

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

This seems really clumsy.. is there another way that I'm missing?

这看起来真的很笨拙..还有我想念的另一种方式吗?

回答by John Earles

Here is a fiddle that demonstrates incrementing:

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

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

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

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

如您所见,self.num(self.num() + 1);确实有效。

回答by Nerdroid

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

回答by Rafael Eyng

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.

如果您使用大量增量,我建议您创建一些辅助函数来进行增量并将其传递给您的 observable 的引用。您最终会得到更具可读性的代码。

JS:

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:

HTML:

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

JSFiddle example

JSFiddle 示例