在循环中更改值后绑定不会更新

时间:2013-07-11 17:39:21

标签: javascript knockout.js

对于我正在处理的小型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>

鉴于图书馆的受欢迎程度以及团队合作的能力,我确信这是我做错了......

1 个答案:

答案 0 :(得分:1)

只需用

替换所选功能
self.unselect = function() {
    self.selected(false);
}

永远不要替换可观察对象。始终将值调用为具有新值的函数。