Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autonomous updating of display in knockoutjs

Tags:

knockout.js

How do I display and update the time without a user-generated event? Here's my start at it, but I cannot figure out how to get the view to refresh.

function viewModel() {
    this.clock = ko.computed(function() { return new Date().getTime(); }, this).extend({ throttle: 1000 });

};

ko.applyBindings(new viewModel());

with the following HTML:

<span data-bind="text: clock"></span>

Here's the jsfiddle.

like image 280
Gene Golovchinsky Avatar asked Dec 24 '11 08:12

Gene Golovchinsky


People also ask

How do you activate a Knockoutjs model?

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.

What is $data in Knockout?

The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel. folders array.

What is Ko mapping fromJS?

var viewModel = ko.mapping.fromJS(data); This automatically creates observable properties for each of the properties on data .

What is Ko applyBindings?

The ko. applyBindings method activates Knockout and wires up the view-model to the view. Now that we have a view-model, we can create the bindings. In Knockout.js, you do this by adding data-bind attributes to HTML elements.


1 Answers

This seemed to do the trick:

function viewModel() {
    var self = this;

    this.clock = ko.observable(new Date());

    this.tick = function() {
        self.clock(new Date());
    };

    setInterval(self.tick, 3000);
};

ko.applyBindings(new viewModel());

when coupled with this HTML:

<span data-bind="text: clock"></span>
like image 147
Gene Golovchinsky Avatar answered Nov 01 '22 22:11

Gene Golovchinsky