问题
I have an observable array as below..
var myObservableArray = ko.observableArray(["Bungle","George","Zippy"]);
I wish to copy the elements into another observable array but in the following format where type is always unknown..
var anotherObservableArray = ko.observableArray([
{ name: "Bungle", type: "Unknown" },
{ name: "George", type: "Unknown" },
{ name: "Zippy", type: "Unknown" }
]);
If the original myObservableArray changes, anotherObservableArray also needs to change. Any help is sincerely appreciated..
Thanks
回答1:
You can create a view model from original data and then use it (jsfiddle):
var originalArray = ["Bungle","George","Zippy"];
function createItemModel(name) {
var model = {
name: ko.observable(name),
type: ko.observable("Unknown"),
}
model.displayText = ko.computed(function() {
return model.name() + '-' + model.type();
});
return model;
}
var myObservableArray = ko.observableArray(originalArray.map(createItemModel));
var viewModel = {
myObservableArray: myObservableArray,
selected: ko.observable()
};
ko.applyBindings(viewModel);
And use this in the markup (from your second question):
<select data-bind="options: myObservableArray,
optionsText: 'displayText',
value: selected"></select>
Update 1
Updated jsfiddle with changing type for selected item.
来源:https://stackoverflow.com/questions/34453587/converting-the-form-of-an-observable-array-and-displaying-in-select-list