JS knockout increment is observed in a good expressive way

Is there a compact way to increase observed KnockoutJS with high expressiveness, so that the code gain is 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 need a more expressive syntax like:

 counter.increment(); 

This type of API must also take an argument to determine the value of the increment:

 counter.increment(10); counter.increment(-1); 

I did not find anything similar in the official documentation, and other similar questions here only report standard syntax, which, in my opinion, is extremely difficult to read.

+6
source share
1 answer

You can either expand the individual observable to support the increase, 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)); }; 
+7
source

Source: https://habr.com/ru/post/980608/


All Articles