0

I have a loop that changes a Knockout observable variable which is used in a computed variable. I have a span that's binded to that computed variable. When I run it, the UI of that span doesn't change. Integer values are being posted to the console, so I know the computed variable is being processed.

Here is my JS:

var PlayerViewModel = function () {
    var self = this;

    self.NumberOfLoops = ko.observable(0);
    self.StartLoopTime = ko.observable(new Date());

    self.LoopsPerMinute = ko.computed(function () {
        var a = self.NumberOfLoops();
        var b = new Date() - self.StartLoopTime();
        var c = a / ((b) / 60000);
        var d = Math.round(c);
        console.log(d);
        return d;
    });

    self.Loop = function () {
        //..Stuff..

        var count = self.NumberOfLoops();
        count = count + 1;
        self.NumberOfLoops(count);

        //..More Stuff..
        //Call self.Loop again
    };
}

HTML:

<span data-bind="text: LoopsPerMinute">0</span>

I have other DOM elements binded to other observables and computeds in 'PlayerViewModel' also and those are working. Shouldn't that spans text be changing automatically while the loop is running. It currently isn't.

Any help is appreciated! Thanks!

user2653364
  • 115
  • 2
  • 8
  • Is your console.log firing? – PW Kad Oct 26 '13 at 22:04
  • Yes, I'm getting a bunch of integers in the console. – user2653364 Oct 26 '13 at 22:23
  • Your code [seems to be working](http://jsfiddle.net/ZZk7J/) for me. – Jeroen Oct 27 '13 at 09:12
  • The problem's somewhere in code you haven't shown, since Jeroen's fiddle shows that the UI does update when you manually force `Loop()` to run. Show the code that's actually calling it (BTW, common JavaScript convention says not to start function names with capitals unless they're constructors that need to be invoked with `new`). – ebohlman Oct 28 '13 at 03:47

1 Answers1

0

You can do it

self.Loop = function () {
    //..Stuff..

    var count = self.NumberOfLoops();
    count = count + 1;
    self.NumberOfLoops(count);

    //..More Stuff..
    setTimeout(function()
    {
       self.Loop();
    }, 0)
};    

JSFiddle DEMO

In this case, view will be updated each time, when self.NumberOfLoops is changed.

Ilya
  • 29,135
  • 19
  • 110
  • 158