【问题标题】:Bindings not updating after changing value in loop在循环中更改值后绑定不更新
【发布时间】:2013-07-12 01:55:18
【问题描述】:

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

鉴于图书馆的受欢迎程度和团队工作的能力,我确定这是我做错的事情......

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    只需将取消选择功能替换为

    self.unselect = function() {
        self.selected(false);
    }
    

    永远不要替换可观察对象。始终使用新值重置作为函数调用它的值。

    【讨论】:

    • 哇 - 我为在此问题上的解决方案的易用性而感到沮丧而感到难为情 :) 非常感谢!
    猜你喜欢
    • 2017-12-08
    • 2023-03-28
    • 2022-09-23
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多