Reputation: 552
I am trying to get some items in an array to update as function of a timer event. But I can't wrap my mind about how to do in in knockout... more I feel a bit knocked-out myself.
The Problem I think is simple, perhaps my approach is wrong, or there simply is something I don't get.
To be a bit more detailed:
The items in the array each represent a time since 'something', to prevent reloading from the server, as you can see, I have bound to the ko.computed(display) function I have defined, which was supposed to take the items.timeElapsed and add the time since the page was loaded, self.moreTimeElapsed()
The html:
<div>
<ul data-bind="foreach: counted">
<li><span data-bind="text: name"></span> - <span data-bind="text: display"></span></li>
</ul>
</div>
and the ViewModel
<script type="text/javascript">
function myViewModel() {
var self = this;
self.email = '[email protected]';
var d = new Date();
self.startTime = d.getTime();
self.moreTimeElapsed = ko.observable(0);
var items = [{"name":"counter1","timeElapsed":168},{"name":"counter2","timeElapsed":162}];
for (i = 0; i < items.length; ++i)
{
items[i].display = ko.computed(function ()
{
return items[i].timeElapsed + self.moreTimeElapsed();
})
}
self.counted = ko.observableArray(items);
self.updateCounters = function () {
var d = new Date();
self.moreTimeElapsed(d.getTime() - self.startTime);
}
setInterval(self.updateCounters, 3000);
};
ko.applyBindings(new myViewModel());
function Reload() {
location.reload(true);
}
</script>
Any hint or ideas appreciated.
Upvotes: 0
Views: 51
Reputation: 552
The problem was with the counter 'i' going out of scope.
i wrapped the code in a closure and that solved the problem
var items = [{"name":"counter1","timeElapsed":1706},{"name":"counter2","timeElapsed":1700}];
var attachDisplayFunc = function(item) {
item.display = ko.computed(function () {
return item.timeElapsed + self.moreTimeElapsed();
})
}
for (i = 0; i < items.length; ++i) {
attachDisplayFunc(items[i]);
}
self.counted = ko.observableArray(items);
So.. is there any way to get notified when making errors as this?
Upvotes: 3