首页 文章

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

提问于
浏览
2

我有一个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调用 . BTW我是Knockout.js的新手 .

这是我在JSFiddle的尝试,但我无法完全发挥作用 . 添加项目工作正常,但是当我更新时,如果我有不同数量的项目...更少项目未被更新的项目被销毁 . 无论如何围绕这个?我不想获取没有任何变化的数据 .

1 回答

  • 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>
    

相关问题