首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据可观察到的变化更新相关属性

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

Stack Overflow用户
提问于 2013-07-22 17:31:24
回答 1查看 90关注 0票数 2

更新

我最初的帖子很长-这是tl;dr版本:

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

-更多细节--

我在用KnockoutJS。我有一个动物园和一个塔皮尔模型和三个观察模型-动物园,tapirCatalog和currentTapir。tapirCatalog是从服务器填充的,currentTapir保存了当时正在编辑的哪个tapir的值。

下面是我想要完成的任务:一个用户在动物园里添加了一个挂毯。当观看动物园时,用户可以编辑一个挂毯,并将其替换为另一个。为此,弹出窗口将显示一个select表单,其中填充tapir名称,而span则显示当前选定的GoofinessLevel。

因此,当select元素更改时,这将更改currentTapir中的currentTapir。我希望这能触发改变当前to的名称和GoofinessLevel的东西。

我尝试订阅currentTapir().GoofinessLevel,但无法让它触发:

代码语言:javascript
复制
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级别时,我得到了触发器:

代码语言:javascript
复制
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"

代码语言:javascript
复制
<select
    data-bind="attr: { id: 'tapirName', name: 'TapirId' },
        options: $root.tapirCatalog,
        optionsText: 'Name',
        optionsValue: 'TapirId',
        value: TapirId">
</select>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-22 21:07:17

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

代码语言:javascript
复制
<select
    data-bind="attr: { id: 'tapirName', name: 'TapirId' },
        options: $root.tapirCatalog,
        optionsText: 'Name',
        optionsValue: 'TapirId',
        value: currentTapir">
</select>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17793778

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档