您如何更新 ko.observableArray 中的项目值并重新绑定?

Posted

技术标签:

【中文标题】您如何更新 ko.observableArray 中的项目值并重新绑定?【英文标题】:How do you update item value(s) in ko.observableArray and rebind? 【发布时间】:2014-06-16 04:26:14 【问题描述】:

我有一个 ko.observableArray,当页面初始化时,会添加 1 个项目。然后,我使用 a 和 data-bind="foreach items" 为 ko.observableArray 中的每个项目创建一个 div。我在页面上有一个按钮和文本框,当您将文本添加到输入并单击该按钮时,一个新项目会被推送到 ko.observableArray。这很好用,我可以在每次单击按钮时添加一个新项目。 ko.observableArray 中的项目有一个与之关联的价格,并且价格会发生变化。我想更新价格,同时仍然能够向 ko.observableArray 添加新项目。价格和商品名称也是 ko.observable。

self.items= ko.observableArray(ko.utils.arrayMap(items, function(item) return name: ko.observable(item.name), price: ko.observable(item.price) ;

如何更新基础项目值(价格)而不重新创建 ko.observable 数组?我是否必须遍历 ko.observable 数组中的每个项目?数据来自 JSON 调用。顺便说一句,我是 Knockout.js 的新手。

这是我对JSFiddle 的尝试,但我无法让它完全正常工作。添加一个项目可以正常工作,但是当我更新时,如果我有不同数量的项目..就像更少的项目一样,没有更新的项目会被销毁。无论如何围绕这个?我不想获取其中没有任何更改的数据。

【问题讨论】:

简单方法:不要重新绑定。使用相同的可观察数组。映射插件支持更新现有数组项:请参阅plugins-mapping 并注意键/更新映射。 (你当然可以手动做同样的事情,但尽可能避免创建新的 observables - 这只会让 KO 脾气暴躁,更难处理。) 好的,我查看了插件映射,有点迷茫,因为我是淘汰赛新手,想保持简单。我将对插件进行深入阅读。 您能否在您的问题中创建一个更完整(尽管尽可能简短)的示例?即使没有 ko-mapping(尽管如此,这是一个很好的建议),我们也可能会为您提供帮助,但很难想象您的上下文。 此外,如果您还可以将该代码发布在显示您的场景的小提琴中,那么提供帮助会更容易。 在 JS 小提琴上工作 【参考方案1】:

改为这样做

javascript

var itemObject = function(data)
    var self = this;

    //I recommend using the mapping plugin
    //ko.mapping.fromJS(data, , self);

    //If you use the mapping plugin, you don't have to hand bind each property
    this.Id = ko.observable(data.Id);
    .... etc ....
;

var baseViewModel = function()
    var self = this;

    this.Items = ko.observableArray();

    this.Setup = function(items)
        //using underscore.js to map the items.
        //This turns each item into an "itemObject", which you can 
        //then manipulate and have all changes shown on the screen, even 
        //inside the array.
        self.Items(_.map(items, function(item)
            return new itemObject(item);
        ));
    ;
;

$(function()
  var myApp = new baseViewModel();
  myApp.Setup(items);
  ko.applyBindings(myApp);
);

html

<div data-bind="foreach: Items">
    <div data-bind="text: Id"></div>
    <!-- other binding things here -->
</div>

【讨论】:

我会试试这个方法,我会告诉你我的结果。

以上是关于您如何更新 ko.observableArray 中的项目值并重新绑定?的主要内容,如果未能解决你的问题,请参考以下文章

为啥 ko.ObservableArray 中的替换值没有更新我的视图?

observableArray未通过完整数组传递更新

如何将 json 字符串转换为 ko.observableArray([]),他们得到一个错误数据未定义?

为什么这个knockoutjs observableArray不会导致UI更新?

Knockoutjs递归地展开ko.observableArray

如何创建双向 ko.computed() 数组过滤器