好的,我有相当多的分层数据。
1份以上
然后我有一个有效的下拉列表
<p data-bind="visible: Id">
Race:
<select data-bind="options: $parent.data.Races, optionsText: 'Name' , optionsValue: 'Id', value: RaceId, optionsCaption: 'Choose...'"></select>
</p>
但是使用 raceId 查找有效性别进行绑定不起作用,因为上下文不会随 with 绑定而更改。
<p data-bind="with: $parent.data.Races()[ RaceId ]">
<pre data-bind="text: ko.toJSON($data,null , 2) "></pre> //debug
Gender:
<select data-bind="options: Genders, optionsText: 'Name' , optionsValue: 'Id', value: $parent.Gender, optionsCaption: 'Choose...'"></select>
</p>
注意的是 with 无法改变上下文,一切都是可观察的。
我想过用一个函数来做到这一点,但这也有点棘手,因为它需要在 raceId 更改时进行更改(并且当未设置 raceId 时,要么隐藏要么为空列表)
任何帮助将不胜感激。
这是我当前的函数尝试(是的,我是javascript的新手),尽管绑定会更加优雅。
self.getGenderForRace = ko.computed( function () {
if ( this && this.data) {
return this.data.Races()[this.RaceId].Genders;
} else {
return new Array();
}
deferEvaluation: true;
}, this);
这是我的一些视图模型
l6.CreateViewModel = function (options) {
var self = this;
//this.getGenderForRace = ko.computed(function (character) {
// return this.data.Races()[character.RaceId].Genders;
//}, this);
self.getGenderForRace = ko.computed( function () {
if ( this && this.data) {
return this.data.Races()[this.RaceId].Genders;
} else {
return new Array();
}
deferEvaluation: true;
}, this);
self.setData = function (url, raceId, factionId, viewmodel) {
$.getJSON(url, { raceId: raceId, factionId: factionId }, function (data) {
viewmodel.data = ko.mapping.fromJS(data.Data);
ko.applyBindings(viewmodel); // we dont bind till we get data
// add to strcture and map!
//self.data = data.Data;
$("#tabContainer").tabs();
});
如果你像我在我的项目中所做的那样分解了数据,根据每个选择,你必须进行ajax调用,这里有一个如何做到这一点的例子。
http://jsfiddle.net/Zholen/h7j3f/
这是一个工作小提琴,演示了一种执行您正在寻找的方法: http://jsfiddle.net/jearles/Q8kcs/
你有什么理由弄乱 ID 吗? 使用选择值绑定可以保存整个选定的可观察量。 这使我们能够轻松访问可用的子选项。
如果要包含deferEvaluation: true
,则应将其作为选项传递给ko.computed
:
self.getGenderForRace = ko.computed({
read: function() {
if ( this && this.data) {
return this.data.Races()[this.RaceId].Genders;
} else {
return [];
}
},
deferEvaluation: true
}, this);