简体   繁体   English

推入ko.observableArray不更新UI

[英]pushing into ko.observableArray not updating the UI

I have a 2 view models 我有2个视图模型

function group(){
name = "";
description = "";
members = ko.observableArray([]);
}

and

function groupTypes(){
gorupA = ko.observableArray([]);
groupB = ko.observableArray([]);
}

I have a regular JS array groupArray with group type objects as elements. 我有一个常规的JS数组groupArray其中有group类型对象作为元素。

I've separate templates for groupA-template and groupB-template 我为groupA-templategroupB-template

I did: 我做了:

var groupTypeInstance = new groupTypes;
groupTypeInstance.groupA.push(groupArray.slice(0,4));
ko.applyBindingsToNode(
            document.getElementById('group-a'),
            {
                template: {
                    name: "groupA-template",
                    foreach: groupTypeInstance.groupA
                }
            }
        );

This displayed the UI correctly. 这样可以正确显示用户界面。 But afterwards when I do groupTypeInstance.groupA.push(groupArray[5]) , nothing happens. 但是之后,当我执行groupTypeInstance.groupA.push(groupArray[5]) ,什么也没发生。 UI doesnt change. UI不变。 Console doesn't show any error. 控制台未显示任何错误。 Array has the extra element when I print it in console. 当我在控制台中打印时,数组具有多余的元素。 Why is the UI not getting updated? 为什么UI无法更新?

Please ask for more details if needed. 如果需要,请询问更多详细信息。

Your code as it is do not work. 您的代码不起作用。 You misspelled groupA and forgot the this. 您拼错了groupA并忘记了this. on the variables. 在变量上。 Also, you cannot add individual array itens to another array by calling push() (it will work but not as you probably intended). 同样,您不能通过调用push()将单个数组iten添加到另一个数组中(它可以工作,但可能并非您预期的那样)。 Here is the code to do what you want, based on what you posted: 这是根据您发布的内容执行所需操作的代码:

 $(function(){ function group(){ this.name = ""; this.description = ""; this.members = ko.observableArray([]); } function groupTypes(){ this.groupA = ko.observableArray([]); this.groupB = ko.observableArray([]); } var groupArray = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6"] ; var groupTypeInstance = new groupTypes(); groupTypeInstance.groupA.push.apply(groupTypeInstance.groupA, groupArray.slice(0,4)); ko.applyBindingsToNode( document.getElementById('group-a'), { template: { name: "groupA-template", foreach: groupTypeInstance.groupA } } ); setInterval(function(){ groupTypeInstance.groupA.push(groupArray[5]); }, 1000); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/html" id="groupA-template"> <h3 data-bind="text: $data"></h3> </script> <div id="group-a"> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM