简体   繁体   English

淘汰观察性观察性数组

[英]knockout observablearray of observables

I am having problems with a Knockout ObservableArray that is made up of objects with observable properties. 我遇到了由具有可观察属性的对象组成的Knockout ObservableArray。 My view model is fairly complicated but I have created the simple test below which will illustrate the problem. 我的视图模型相当复杂,但是我在下面创建了一个简单的测试来说明问题。

My problem is that when I change the value of an observable property in one of the objects in the ObservableArray that value is changed for ALL objects in the array. 我的问题是,当我更改ObservableArray的对象之一中的observable属性的值时,该值将更改为数组中的所有对象。

I have a department viewModel which has an observable array of employees in that department. 我有一个部门viewModel,该部门中有一个可观察的雇员数组。 I then create 5 instances of the object personVM that gets pushed onto the employees ObservableArray. 然后,我创建对象personVM的5个实例,该实例被推送到员工的ObservableArray上。 Each instance of personVM gets a unique firstName. 每个personVM实例都有一个唯一的firstName。

Here are the models and the code to load them up. 这里是模型和加载它们的代码。

var theDepartmentVM = {
        employees: ko.observableArray(), 
        departmentName: ko.observable()
};

var personVM= {
    firstName: ko.observable()
    }

$(document).ready(function (){
    departmentVM.departmentName = "SomeDepartment";
    for (i=1; i<=5; i++){
        var person = Object.create(personVM);
        personVM.firstName("EMP - " + i.toString());
        departmentVM.employees.push(personVM);
    }
    ko.applyBindings(departmentVM);
});

This adds five name (EMP-1, EMPT-2, etc.). 这将添加五个名称(EMP-1,EMPT-2等)。 Then I display the names with the following markup: 然后,我用以下标记显示名称:

<div data-bind="foreach: employees">
   <label data-bind="text: firstName"></label>
</div>

My output is the name "EMP-5" five times. 我的输出是名称“ EMP-5”的五倍。 It's always the last value I added to the array. 它始终是我添加到数组中的最后一个值。

I think the problem is that I have five instances of personVM but the firstName object in each instance points to the same observable. 我认为问题是我有五个personVM实例,但是每个实例中的firstName对象都指向相同的可观察对象。 Is this correct? 这个对吗?

What do I need to do to get the desired result? 我需要怎么做才能获得理想的结果?

Try this 尝试这个

http://jsfiddle.net/r9sqjojL/2/ http://jsfiddle.net/r9sqjojL/2/

<div data-bind="foreach: employees">
   <label data-bind="text: firstName"></label>
</div>
var departmentVM = {
        employees: ko.observableArray(), 
        departmentName: ko.observable()
};

var personVM = function() {
        this.firstName = ko.observable();
}
departmentVM.departmentName = "SomeDepartment";
for (i=1; i<=5; i++){
        var person = new personVM();
        person.firstName("EMP - " + i.toString());
        departmentVM.employees.push( person );
}
ko.applyBindings(departmentVM);

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

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