Reputation: 576
I have a problem to show different content for different datetime
with knockout foreach
binding.
Everything is working good, but a major problem is with the functions showData
and getDataByCurrentDate
I created some example code to show what I'm trying to do:
This is my JavaScript code:
var data = { "Blog": [
{
"date":"07/09/2012",
"title":"Title 1",
"content":"Text 1"
},
{
"date":"08/09/2012",
"title":"Title 2",
"content":"Text 2"
},
{
"date":"09/09/2012",
"title":"Title 3",
"content":"Text 3"
},
{
"date":"10/09/2012",
"title":"Title 4",
"content":"Text 4"
}
]
};
var current = new Date();
function formatCurrentDate() {
return ('0' + current.getDate()).slice(-2) + '/' + ('0' + (current.getMonth() + 1)).slice(-2) + '/' + current.getFullYear();
}
function getDataByCurrentDate() {
var output = [];
for(var i in data.Blog) {
if(data.Blog[i].date== formatCurrentDate()) {
output.push(data.Blog[i]);
}
}
return output;
}
function showData(data) {
var output = 'No data';
if(data.length > 0) {
for(var i in data) {
self.findDataBlog.push(data1[x]);
}
}
}
function loadData() {
var data = getDataByCurrentDate();
showData(data);
showCurrentDate();
}
function showCurrentDate() {
document.getElementById('currentDate').innerHTML = formatCurrentDate();
}
window.onload = function() {
loadData();
document.getElementById('next').onclick = function() {
current.setTime(current.getTime() + 1000*60*60*24);
loadData();
return false;
}
document.getElementById('previous').onclick = function() {
current.setTime(current.getTime() - 1000*60*60*24);
loadData();
return false;
}
}
This is the body
tag:
<a href="#" id="previous"> << </a>
<span id="currentDate"></span>
<a href="#" id="next"> >> </a>
<div data-bind="foreach: findDataBlog">
<ul>
<li>
<a>
<h1><span data-bind="text: title"></span></h1>
<p>
<span data-bind="date: date"></span>
<span data-bind="text: content"></span>
</p>
</a>
</li>
</ul>
</div>
Upvotes: 0
Views: 328
Reputation: 10147
I have created a working jsFiddle for you here: http://jsfiddle.net/ruslans/Y58DJ/
The main changes I've made is introduced a knockout viewModel
variable and fixed errors in showData()
function:
var myViewModel = {
findDataBlog = ko.observableArray();
}
ko.applyBindings(myViewModel);
...
function showData(data) {
myViewModel.findDataBlog.removeAll()
if (data.length > 0) {
for (var i in data) {
myViewModel.findDataBlog.push(data[i]);
}
}
}
amended html:
<a href="#" id="previous"> << </a><span id="currentDate"></span>
<a href="#" id="next"> >> </a>
<br />
<span data-bind="visible: findDataBlog().length == 0">no data</span>
<div data-bind="foreach: findDataBlog, visible: findDataBlog().length > 0">
<ul>
<li> <a>
<h1><span data-bind="text: title"></span></h1>
<p>
<span data-bind="date: date"></span>
<span data-bind="text: content"></span>
</p>
</a>
</li>
</ul>
</div>
Upvotes: 1
Reputation: 1242
//findDataBlog should be declare as observable array.
var findDataBlog = ko.observableArray();
// Please try with this.
Upvotes: 0