I have created two observables variables on Knock Out as follow:
self.winImage1= ko.observable();
self.winImage2= ko.observable();
And validated and stored platform based CSS for the observable variables in JS as follow:
self.findOperatingSystem = function (data) {
if (navigator.appVersion.indexOf("Win") != -1) {
data.winImage1("window_icon_1_css");
data.winImage2("windows_icon_2_css");
}
else if (navigator.appVersion.indexOf("Mac") != -1){
data.winImage1("mac_icon_1_css");
data.winImage2("mac_icon_2_css");
}
}
And then tried to add the observable variables to HTML as a class as follows:
<div class="some_class1" data-bind="visible: $root.DeviceModel.findOperatingSystem ($parent)">
<i data-bind="foreach: $data.winImage1()"></i>
<i data-bind="foreach: $data.winImage2()"></i>
</div>
But getting error while using foreach. Someone, please help to identify what am doing wrong here. Suspect using wrong data-bind!
please help me to solve this.
The problem is that foreach does not work like that. You will need an array of observables to work with it like so:
self.itemsArray = [ko.observable({ id: 1, name: 'image1'}), ko.observable({id:2, name:'image2'})];
self.winImages = ko.observableArray(itemsArray );
<div class="some_class1" data-bind="visible: $root.DeviceModel.findOperatingSystem($parent), foreach: winImages ">
<i data-bind="attr: { id: $data.id}"></i>