根据可观察到的变化更新相关属性

Update related properties in response to observable change

本文关键字:更新 属性 变化 观察      更新时间:2023-09-26

更新

我原来的帖子很长——这是tl;dr版本:

在单个属性发生更改后,如何更新淘汰模型的所有属性?update函数必须引用viewModel中的observableArray

--更多详细信息——

我正在使用KnockoutJS。我有一个Zoo和一个Tapir模型,在视图模型中有三个可观察对象——zoos、tapirCatalog和currentTapir。tapirCatalog是从服务器填充的,currentTapir保存当时正在编辑的任何一个tapir的值。

以下是我想要实现的:一位用户将一只tapir从tapir列表中添加到了他/她的动物园。在观看动物园时,用户可以编辑一只tapir并将其替换为另一只。为此,将显示一个弹出窗口,其中包含一个由tapir名称填充的选择表单,以及一个显示当前所选GoofinessLevel的跨度。

因此,当select元素更改时,currentTapir中的TapirId也随之更改。我希望这能触发一些改变当前Tapir的名称和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不应该对动物园有任何了解: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>

听起来你需要做的是将选择绑定到一个可观察的对象,而不是Id

<select
    data-bind="attr: { id: 'tapirName', name: 'TapirId' },
        options: $root.tapirCatalog,
        optionsText: 'Name',
        optionsValue: 'TapirId',
        value: currentTapir">
</select>