【问题标题】:Knockoutjs model does not update when select options change选择选项更改时,Knockoutjs 模型不会更新
【发布时间】:2014-03-13 01:35:04
【问题描述】:

I have a computed function which doesn't update the UI when a select options change.但如果我添加或删除一行,效果很好。

这是 HTML:

<button data-bind="click: add">Add New</button>
<ul data-bind="foreach: items">
    <li>
        <label data-bind="text: name"></label>
        <select data-bind="options: [1,2,3], value: val"> </select>
    </li>
</ul>
TOTAL: <span data-bind="text: total"></span>

这是 JavaScritp:

function viewModel (initialItems) {
    this.items = ko.observableArray(initialItems);

    this.total = ko.computed(function () {
        var total = 0;
        for (var i = 0; i < this.items().length; i++)
            total += this.items()[i].val;
        return total;
    }, this);

    this.add = function() { this.items.push({name: "New", val: 1}); };
}

ko.applyBindings(new viewModel([{name: "Alpha", val: 2}, 
                                  {name: "Beta", val: 3},
                                  {name: "Gamma", val: 1}]));

这里是小提琴:http://jsfiddle.net/waUE4/

选择更改时如何获取模型更新?

感谢您的帮助。

编辑

工作版本:http://jsfiddle.net/fCE3a/1/

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    val 属性没有更新的原因是它没有声明为Observable 属性。

    从 KnockoutJS 官方网站查看这个示例代码,它看起来像你想要做的:Cart editor example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多