根据可观察到的变化更新相关属性
Update related properties in response to observable change
更新
我原来的帖子很长——这是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>
- Css order属性不't在Jquery设置时更新
- 更新属性工作不正常Meteor/MongoDB
- 阵列中的localstorage更新属性
- 数组中嵌入文档的集合更新属性
- Javascript object.defineProperties 以自动更新属性
- 使用 ajax 调用轨道更新属性
- X3DOM 更新属性
- React未从数组内的对象更新属性
- 如何使用 Ember 更新属性后滚动到 DOWN
- 如果JavaScript对象是通过引用传递的,为什么不;t更新属性值更新局部变量
- 余烬模板不更新属性变量的变化
- 如何使用jQuery更新属性?
- 更新属性指令值
- Jquery /js:脚本在输入值改变后不更新属性
- OrientDB通过JavaScript更新属性
- 猫鼬模式方法和“这个”更新属性 - NodeJS
- 不更新属性值的二传手函数
- Backbone.js正在更新属性被更改的模型
- 克隆和更新属性
- 如何在从子控制器更新属性后刷新应用程序模板