Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment a KnockoutJS observable in an good expressive way

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.

like image 412
marcopeg Avatar asked Jan 06 '15 18:01

marcopeg


1 Answers

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));
};
like image 157
Jeff Mercado Avatar answered Oct 17 '22 15:10

Jeff Mercado