更新observableArray项后,knockoutjsisvisible刷新
knockoutjs isvisible refresh after observableArray item has been updated
这是我的简化模型:
var GoalItem = function(id, type, name, authorId, author, children) {
this.id = ko.observable(id);
this.type = ko.observable(type);
this.name = ko.observable(name);
this.authorId = ko.observable(authorId);
this.author = ko.observable(author);
this.children = ko.observableArray(children || []);
this.isPage = ko.computed(function(){ return type == 'page' ? true : false; }, this);
this.isFile = ko.computed(function(){ return type == 'file' ? true : false; }, this);
};
var GoalModel = function() {
this.list = ko.observableArray([
new GoalItem(1, 'page', 'Getting started', 0, '', [
new GoalItem(2, 'page', 'Getting started 1.1', 0, ''),
new GoalItem(3, 'video', 'Video', 0, '', [
new GoalItem(4, 'data', 'Data', 0, ''),
new GoalItem(5, 'test', 'Test', 0, '', [
new GoalItem(6, 'page', 'Test prep', 0, '', [
new GoalItem(7, 'video', 'Test video', 0, ''),
new GoalItem(8, 'file', 'Test file', 0, '')
])
]),
new GoalItem(9, 'page', 'Sample page', 0, '')
])
]),
new GoalItem(10, 'page', 'More data tracking', 0, '', [
new GoalItem(11, 'data', 'Data 1', 0, ''),
new GoalItem(12, 'data', 'Data 2', 0, '')
])
]);
}
一些标记使用isvisible来确定显示的html片段
<div data-bind="visible: currentItem().isPage">
applicable to pages only
</div>
与。
<div data-bind="visible: currentItem().isFile">
applicable to files only
</div>
我有一些代码,当用户点击一个GoalItem时,它会加载到树视图中,并且isvisible会处理显示/隐藏
如果用户现在在UI中更改当前GoalItem的"type"属性,则不应重新触发isvisible-因此,如果类型从"page"更改为"file"
目前它似乎不起作用,希望这个解释有意义,如果没有,我会尝试添加更多细节。
另一方面,在阅读过程中,我是否必须"删除"或"替换"可观察数组中的项目,以使其重新触发isvisible:binding?如果是,或者作为一个相关的问题,基于this.id在observableArray中查找项目的最佳方式是什么?记住该项目可能在子对象中"深层"?
任何反馈或帮助都将不胜感激
您计算的可观察性将触发UI更新,但它们并不完全正确:
this.isPage = ko.computed(function(){ return type == 'page' ? true : false; }, this);
this.isFile = ko.computed(function(){ return type == 'file' ? true : false; }, this);
这些应该看起来更像:
this.isPage = ko.computed(function() {
return this.type() == 'page' ? true : false;
}, this);
this.isFile = ko.computed(function() {
return this.type() == 'file' ? true : false;
}, this);
现在,您实际上已经访问了可观测值,因此计算的可观测值依赖于type
可观测值。当它发生变化时(通过将其值设置为this.type('file');
,将重新评估计算出的可观测值,并通知任何订阅者(您的UI)。
相关文章:
- 没有找到相关文章