Is there a compact way to increment a KnockoutJS observable in a high expressive way so the code gain in readability?
I would like to avoid this syntax:
var counter = ko.observable(0);
// increment the counter as we know today
counter(counter() + 1);
Instead I would like a more expressive syntax like:
counter.increment();
This kind of API should also accept an argument to define the value of the increment:
counter.increment(10);
counter.increment(-1);
I didn't found anything like this in the official documentation and other similar questions here report just the standard syntax which in my opinion is extremely difficult to read.
You could either extend the individual observable to support incrementing or apply it to all observables.
// for individual
ko.extenders['incrementable'] = function (target, enabled) {
if (enabled) {
target.increment = function (incValue) {
this(this() + (incValue || 1));
}.bind(target);
}
return target;
};
var counter = ko.observable(0).extend({ incrementable: true });
counter.increment();
// or for all
ko.observable.fn.increment = function (incValue) {
this(this() + (incValue || 1));
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With