I would need help in linking a Date object in a JsViews Template

105 Views Asked by At

I am writing a small javascript game... to set in-game time, I have variable that holds the current in-game date and time, I want to display this date and every seconds, increase that date with hours.

I am using JSViews for the databinding and it works well in the application except for that date and I don't understand !! I have created a JSFiddle that represents the idea:

http://jsfiddle.net/ClaudeVernier/w8cwkarr/5/

try {
    var tmplDates = $.templates("#tmplDates");
    tmplDates.link("#gameSet", model);

    gameLoop();
}
catch(e) {
    alert(e);
}

I have a data model with a date and an integer. I have a Template that shows the data model using converters

<script id="tmplDates" type="text/x-jsrender">
    <hr /> <span data-link="{toDateString:gameDate}"></span>
    <hr /> <span data-link="{toTimeString:gameDate}"></span>
    <hr /> <span data-link="{toString:gameInt}"></span>
</script>

and every seconds, I update both the date and the integer with the Observable method. The integer gets updated but not the date !

function gameLoop() {
    var tDate = model.gameDate;
    tDate.addHours(4);

    $.observable(model).setProperty("gameDate", tDate);

    var tInt = model.gameInt + 1;
    $.observable(model).setProperty("gameInt", tInt);

    $("#lastUpdate").text( gameDateString(model.gameDate, 0) + "-" + gameDateString(model.gameDate, 6) + " - [" + model.gameInt + "]");

    window.setTimeout(gameLoop, 1000);
}

I added a line where I write the value without databinding to show that the values are updated..

1

There are 1 best solutions below

1
On

The problem here is that you are passing the same date object every time.

var tDate = model.gameDate;
tDate.addHours(4);
...
$.observable(model).setProperty("gameDate", tDate);

JsViews setProperty() raises a 'change event' when you set a different value to the current one on that path. (i.e. if you modify the value of the gameDate on the model). Here the value is the same date object that is already on your model so there will be no change event, and no updated value.

So one fix is to make tDate a new object each time:

var tDate = new Date(model.gameDate);
tDate.addHours(4);
...
$.observable(model).setProperty("gameDate", tDate);

Another fix would be to make the gameDate on the model be a string - the Date.valueOf().

I created an update from your jsfiddle here:

http://jsfiddle.net/w8cwkarr/6/