Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you increment a knockout.js observable?

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?

like image 836
Jeremy Smith Avatar asked Mar 03 '12 18:03

Jeremy Smith


People also ask

How do I set observable value in knockout?

To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.

What is Ko observable ()?

An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted. The main advantage of KO is that it updates our UI automatically when the view model changes.

What activates knockout in JS?

To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.


3 Answers

Here is a fiddle that demonstrates incrementing:

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

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

like image 82
John Earles Avatar answered Oct 08 '22 23:10

John Earles


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
like image 43
Nerdroid Avatar answered Oct 08 '22 23:10

Nerdroid


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.

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)">

JSFiddle example

like image 42
Rafael Eyng Avatar answered Oct 09 '22 00:10

Rafael Eyng