对于我正在处理的小型 Knockout 屏幕,我有以下 ViewModel。在 UI 中有一个“取消”按钮,它调用viewModel.cancel()
(如下)。该cancel
函数完成了它应该做的事情(从一个集合中删除项目并遍历另一个集合以设置选定的属性),但 UI 永远不会更新。
var tag = function(id, text){
var self = this;
self.id = id;
self.text = text;
self.selected = ko.observable(false);
self.unselect = function() {
self.selected = false;
}
};
var viewModel = function() {
var self = this;
self.tags = ko.observableArray([
new tag(100, "Tag100"),
new tag(200, "Tag200"),
new tag(300, "Tag300"),
new tag(400, "Tag400"),
new tag(500, "Tag500"),
new tag(600, "Tag600")
]);
self.selectedTags = ko.observableArray();
self.childClick = function(tag){
self.selectedTags.remove(tag);
if (tag.selected){
self.selectedTags.push(tag);
}
return true;
};
self.showApply = ko.computed(function() {
return self.selectedTags().length > 0;
});
self.cancel = function(){
this.selectedTags.removeAll();
ko.utils.arrayForEach(this.tags(), function(tag) {
tag.unselect();
});
//when this finishes, selectedTags is empty and calling ko.toJSON(viewModel) shows that the selected value is reset -- the UI just doesn't reflect this.
};
};
html相当简单
<div id="tagDropdown" class="btn-group">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
Add Tag<span class="caret"></span>
</a>
<ul class="dropdown-menu dropdown-menu-form">
<li data-bind="foreach: tags">
<div>
<div class="tagCheck"><input type="checkbox" data-bind="value: id, checked: selected, click: $root.childClick" /></div>
<div class="tagText" data-bind="text: text"></div>
</div>
</li>
<li>
<div class="separator"></div>
<button data-bind="visible: showApply">Apply</button>
<button data-bind="visible: showApply, click: cancel">Cancel</button>
</li>
</ul>
</div>
鉴于图书馆的受欢迎程度和团队工作的能力,我确信这是我做错的事情......