更新observableArray不会更新UI [英] Updating an observableArray does not update UI

查看:93
本文介绍了更新observableArray不会更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ko 2.0中使用无容器流量控制.当我更新observableArray中的项目时,它不会更新UI.我正在像这样更新数组:

I am using the containerless flow control in ko 2.0. When I update an item in my observableArray it is not updating the UI. I am updating the array like this:

this.editFormHost = function (formHost) {
    ...
    formHost.HostName = newHostName;
    this.formHosts[index] = formHost;
}

我认为它不会更新,因为通过索引更新数组不会调用ko中的任何内容.通过查看文档,似乎没有任何更新对象的方法,这些方法又会更新UI.还是在那里?

I am thinking it doesn't update because updating the array by index does not call anything in ko. From looking at the documentation it looks like there are no methods to update an object which will in turn update the UI. Or is there?

推荐答案

此处是一个小提琴,它演示了如何替换observableArray中的项目以及如何将其更改通知UI.

Here is a a fiddle that demonstrates how to replace an item in an observableArray and have its changes notify the UI.

http://jsfiddle.net/johnpapa/ckMJE/

这里的关键是observableArray上的replace函数.您也可以使用拼接.

The key here is the replace function on the observableArray. You could also use splice.

...请注意在下面使用替换" ...

... Notice the use of "replace" below ...

var ViewModel = function() {
    this.self = this;
    self.index = ko.observable(0); // default
    self.newColor = ko.observable("purple"); // default
    self.colors = ko.observableArray([{
        color: 'red'},
    {
        color: 'blue'},
    {
        color: 'yellow'}]);
    self.replaceIt = function() {
        self.colors.replace(self.colors()[self.index()], {
            color: self.newColor()
        });
    };
};
ko.applyBindings(new ViewModel());

这篇关于更新observableArray不会更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆