I am using KnockoutJS to create a simple rotate animation. I have some items that contain a title and a description and I’m cycling trough these items.
Beneath the title and description I show some paging buttons and the active button should have a style applied.
However, the style for the paging button is not updated. Currently all paging buttons have the style applied instead of only styling the active page. I have created a jsFiddle that shows my problem.
What am I doing wrong?
JavaScript:
var AppViewModel = function () {
this.currentItem = ko.observable();
this.items = ko.observableArray([
new Item("titleA", "descriptionA"),
new Item("titleB", "descriptionB"), ]);
this.tick = function () {
var item = this.items.shift();
if (item) {
item.visible(false);
this.items.push(item);
}
this.items()[0].visible(true);
};
this.tick();
setInterval(function () {
_this.tick();
}, 1000);
}
var Item = function (title, description) {
this.title = title;
this.description = description;
this.visible = ko.observable(false);
}
ko.applyBindings(new AppViewModel());
HTML:
<div data-bind="foreach: items">
<div data-bind="visible:visible"> <span data-bind="text: title"></span>
<blockquote data-bind="text: description"></blockquote>
</div>
</div>
<nav>
<ul data-bind="foreach: items">
<li data-bind="style: { color: visible ? 'red' : 'black'} ">X</li>
</ul>
</nav>
I think that when you are using an observable in a test condition, you need to call it properly, as otherwise what you asking it to resolve is whether visible is a truthy condition in js, which a function is:
This seems to fix it for me in your jsFiddle.