So I have 2 view models, one that houses an array I use that binds each data node in dataList to the form, and the other is used as a model for each data node. I'm trying to update the array in the first viewmodel with the data from the second:
HTML:
<div data-bind="foreach:mainArray">
<select data-bind="options: $root.ourTypes, optionsValue: 'ID', optionsText: 'Name', value: $data.OurTypeId"></select>
</div>
JavaScript:
var dataList = [
{ OurTypeId: 4 }, // there are other values here...
{ OurTypeId: 2 }, // and here...
{ OurTypeId: 3 } // and here...
];
var ourTypes = [
{ ID:"1", Name:"None", Limit:0 },
{ ID:"2", Name:"Fruits", Limit:5 },
{ ID:"3", Name:"Vegetables", Limit:5 },
{ ID:"4", Name:"Meats", Limit:2 }
];
var myViewModel = new MyViewModel(dataList);
ko.applyBindings(myViewModel);
function MyViewModel(dataList) {
var self = this;
self.ourTypes = ourTypes;
self.mainArray = ko.observableArray([]);
if (dataList.length > 0) {
for (var i=0; i<dataList.length; i++) {
var myDataViewModel = new MyDataViewModel(dataList[i]);
//alert(myDataViewModel.OurType);
self.mainArray.push(myDataViewModel);
}
}
}
function MyDataViewModel(vm) {
var self = this;
if (vm != null) {
var myType = "";
for (var i=0; i<ourTypes.length; i++) {
if (ourTypes[i].ID == vm.OurTypeId)
myType = ourTypes[i].Name;
}
self.OurTypeId = ko.observable(vm.OurTypeId);
self.OurType = myType;
} else {
self.OurTypeId = 0;
self.OurType = "";
}
self.OurTypeId.subscribe(function(newValue) {
var updatedItem = 0;
var newName = "";
for (var i=0; i<ourTypes.length; i++) {
if (ourTypes[i].ID == newValue) {
self.OurType = ourTypes[i].Name;
// alert(ourTypes[i].Name);
updatedItem = i;
}
}
// I want to do something like this to update "OurType" in mainArray...
// var theList = MyViewModel.mainArray();
// theList[updatedItem].OurType = self.OurType;
// MyViewModel.mainArray(theList);
});
}
This is actually a slimmed-down version of the code that just focuses on "ourTypes", my fiddle has a little more. I use the ID on the dropdown to indicate a change in the model, but then I have to update the actual name of the type manually (you'll see how the name does not update when the ID does in my fiddle), so I attempt to do that in a .subscribe() function, but nothing seems to work. Any ideas?