我无法让选择填充对象中属性的初始值。
我有一个Location
对象,它的属性是urls
.
{ id: 1, name: 'Location1', state: 'md', headline: 'headline1', urls: [{ id: 1, url: 'www.google.com', type: { id: 1, type: 'Public'} }]}
当用户选择Location
我试图url.type.type
在列表中显示为选定选项时,它始终显示optionsCaption
.
请在我的小提琴中找到完整的例子
var seedData = [
{ id: 1, name: 'Location1', state: 'md', headline: 'headline1', urls: [{ id: 1, url: 'www.google.com', type: { id: 1, type: 'Public'} }]},
{ id: 2, name: 'Location2', state: 'va', headline: 'headline2', urls: [{ id: 1, url: 'www.bing.com', type: { id: 2, type: 'Private'} }]},
{ id: 3, name: 'Location3', state: 'md', headline: 'headline3', urls: [{ id: 1, url: 'www.yahoo.com', type: { id: 1, type: 'Public'} }]}
];
function UrlType(data) {
this.id = ko.observable(data.id);
this.type = ko.observable(data.type);
}
function Url(data) {
this.id = data.id;
this.url = ko.observable(data.url);
this.type = ko.observable(new UrlType(data.type));
}
function Location(data, types, names) {
var self = this;
self.id = data.id;
self.name = ko.observable(data.name).extend({ maxLength: 10, unique: { collection: names, externalValue: true } });
self.state = ko.observable(data.state).extend({ pattern: '^[A-Za-z]{2}$'});
self.headline = ko.observable();
self.urls = ko.observableArray(ko.utils.arrayMap(data.urls, function(item) {
return new Url(item);
}));
self.errors = ko.validation.group(self);
//update the data at any time
self.update = function(data) {
self.name(data.name);
self.state(data.state);
self.headline(data.headline);
debugger;
self.urls(ko.utils.arrayMap(data.urls, function(item){
return new Url(item);
}));
};
//initialize with our initial data
self.update(data);
};
function ViewModel() {
var self = this;
self.types = [
{ id: 1, name: 'Public' },
{ id: 2, name: 'Private' }
];
self.locations = ko.observableArray([]);
self.selectedLocation = ko.observable();
self.selectedLocationForEditing = ko.observable();
self.names = ko.computed(function(){
return ko.utils.arrayMap(self.locations(), function(item) {
return item.name();
});
});
self.edit = function(item) {
self.selectedLocation(item);
self.selectedLocationForEditing(new Location(ko.toJS(item), self.types, self.names()));
};
self.cancel = function() {
self.selectedLocation(null);
self.selectedLocationForEditing(null);
};
self.update = function(item) {
var selected = self.selectedLocation(),
updated = ko.toJS(self.selectedLocationForEditing()); //get a clean copy
if(item.errors().length == 0) {
selected.update(updated);
self.cancel();
}
else
alert("Error");
};
self.locations(ko.utils.arrayMap(seedData, function(item) {
return new Location(item, self.types);
}));
}
ko.applyBindings(new ViewModel());