更新
我最初的帖子很长-这是tl;dr版本:
在单个属性更改后,如何更新淘汰制模型的所有属性?update函数必须引用viewModel中的一个viewModel。
-更多细节--
我在用KnockoutJS。我有一个动物园和一个塔皮尔模型和三个观察模型-动物园,tapirCatalog和currentTapir。tapirCatalog是从服务器填充的,currentTapir保存了当时正在编辑的哪个tapir的值。
下面是我想要完成的任务:一个用户在动物园里添加了一个挂毯。当观看动物园时,用户可以编辑一个挂毯,并将其替换为另一个。为此,弹出窗口将显示一个select表单,其中填充tapir名称,而span则显示当前选定的GoofinessLevel。
因此,当select元素更改时,这将更改currentTapir中的currentTapir。我希望这能触发改变当前to的名称和GoofinessLevel的东西。
我尝试订阅currentTapir().GoofinessLevel,但无法让它触发:
function Zoo(data) {
this.ZooId = ko.observable(data.ZooId);
this.Tapirs = ko.observableArray(data.Tapirs);
}
function Tapir(data) {
this.TapirId = ko.observable(data.TapirId);
this.Name = ko.observable(data.Name);
this.GoofinessLevel = ko.observable(data.Name);
}
function ViewModel() {
var self = this;
// Initializer, because I get an UncaughtType error because TapirId is undefined when attempting to subscribe to it
var tapirInitializer = { TapirId: 0, Name: "Template", GoofinessLevel: 0 }
self.zoos = ko.observableArray([]);
self.tapirCatalog = ko.observableArray([]);
self.currentTapir = ko.observable(new Tapir(tapirInitializer));
self.currentTapir().TapirId.subscribe(function (newValue) {
console.log("TapirId changed to: " + newValue);
}); // This does not show in console when select element is changed
};奇怪的是,当我订阅Tapir模型中的Goofiness级别时,我得到了触发器:
function Tapir(data) {
var self = this;
self.TapirId = ko.observable(data.TapirId);
self.Name = ko.observable(data.Name);
self.GoofinessLevel = ko.observable(data.Name);
self.TapirId.subscribe(function (newId) {
console.log("new TapirId from internal: " + newId);
}); // This shows up in the console when select element is changed
}我怀疑对于使用KO的人来说,这是一个非常常见的场景,但是我没有找到任何东西。现在我已经搜索了一段时间(可能我没有正确的词汇表可供搜索?)我确实找到了这个解决方案,但他引用了模型本身的视图模型--这看起来像是回编码,因为我认为Tapir不应该对Zoo:http://jsfiddle.net/rniemeyer/QREf3/有任何了解。
**更新**下面是我的select元素的代码(父div有data-bind="with: currentTapir"
<select
data-bind="attr: { id: 'tapirName', name: 'TapirId' },
options: $root.tapirCatalog,
optionsText: 'Name',
optionsValue: 'TapirId',
value: TapirId">
</select>发布于 2013-07-22 21:07:17
听起来你需要做的是将选择绑定到一个可观察的,而不是Id。
<select
data-bind="attr: { id: 'tapirName', name: 'TapirId' },
options: $root.tapirCatalog,
optionsText: 'Name',
optionsValue: 'TapirId',
value: currentTapir">
</select>https://stackoverflow.com/questions/17793778
复制相似问题