Amar Zeno
Amar Zeno

Reputation: 412

Triggering knockout click event multiple times

I am working on a single page phonegap application which uses jquerymobile and knockout.

Inside the JqueryMobile pageInit I have defined the sampleViewModel() as follows.

function sampleViewModel()
{
var self=this;
var hourvalue=14;
self.sample_data= ko.observableArray([
            { title: "hello", hour:hourvalue }    
        ]);
}

//Variable declaration for the above view model

var sample_datavar = { viewModel: new sampleViewModel() };

I want to change the hourvalue based on the current system hour value. Any better solutions for the same is appreciated.

Am trying out the following logic wherein I will get the system hour every second and pass it to the datasource via that variable assignment.

setInterval(function () {
        var now = new Date();
        var hour = now.getHours();
        if (hour.toString().length == 1) {
            var hour = '0' + hour;
        }

sample_datavar.viewModel.sample_data([
            { title: "hello", hour:hourvalue }    
        ]);
  },1000);

Problem is that I can define this only inside a click event which will be inside the pageinit call function.

1)Is there a way to make the knockout click function to trigger inside the pageshow event of jquery mobile?

2)If am complicating things?..Is there a better way of doing that hourvalue changes?

Upvotes: 0

Views: 327

Answers (1)

GôTô
GôTô

Reputation: 8053

First of all, please don't check every second if the hour has changed, it hurts my eyes :) --unless the time of the system is supposed to change unexpectedly.

Then why do you need a click event? Why don't you just start to check at loading and then check again and again?

You can calculate the seconds before the next check (you could event set the new hour without checking):

function sampleViewModel()
{
    var self=this;
    var hourvalue=14;
    self.sample_data= ko.observableArray([
            { title: "hello", hour:hourvalue }    
        ]);
}

var viewModel = new sampleViewModel();
ko.applyBindings(viewModel);

function checkHour() {
        var now = new Date();
        var hour = now.getHours();
        var secondsBeforeNextCheck = 3600 - now.getMinutes() * 60 - now.getSeconds() +1;
        document.getElementById('calculatedSeconds').innerHTML = secondsBeforeNextCheck;
        if (hour.toString().length == 1) {
            var hour = '0' + hour;
        }

        viewModel.sample_data([
            { title: "hello", hour:hour }    
        ]);
        setTimeout(checkHour, secondsBeforeNextCheck * 1000);
}

checkHour();

http://jsfiddle.net/7nBNW/2/

Upvotes: 2

Related Questions