我无法使用select来填充对象中属性的初始值。
我有一个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
。
请在我的fiddle
中找到完整示例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());
答案 0 :(得分:0)
这是一个工作小提琴:http://jsfiddle.net/jearles/2HS5J/5/
我已经引入optionsValue: 'id'
来将该属性作为所选选项拉出,并将seedData简化为仅包含type: 1
(唯一ID,而不是类型对象)。这使得淘汰赛可以轻松地将type
映射到您的$root.types
之一(否则,您必须自己完成此操作)。此外,当optionsText: 'type'
数组包含具有options
属性的对象而不是'type'属性时,您使用的是name
- 这就是为什么knockout无法使用选项填充select。