Converting the form of an observable array and displaying in select list

蹲街弑〆低调 提交于 2020-01-17 06:23:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!