简体   繁体   中英

Add/remove Knockout observableArray nested elements

I'm trying to add to/remove from a nested observableArray in KnockoutJS. I have an array several elements, each with an attribute object, type object and an attributeValue array which holds objects. So it's a nested array.

The allAttributes array is observableArray. Then I tried making the attributeValue array observable by making a new ViewModel (attributeValueViewModel) with attributeValues as ko.observableArray([]).

I made two Knockout functions (which don't work) and I'm trying to add/remove values to/from that array. The problem is that the array is nested so I have to access the attributeID through this.attribute.id. self.allAttributes[i].attributeValues[j] should be the object I'm adding/removing... where i=attributeID and j=index of the attribute's value object

Why aren't those functions working?

Here is my fiddle: http://jsfiddle.net/M6Hqj/2/

First off, you're overwriting the observable function in your inner view model, eg when you assign obj.attribute = item.attribute; , you're overwriting your initial assignment of self.attribute = ko.observable(data.attribute); . Instead assign the value through the observable, like so:

obj.attribute(item.attribute); //instead of obj.attribute = item.attribute;

This will also make your self.addAttributeValue() function call work since the array is now observable.

Next, in your self.removeAttributeValue() function, the this call actually refers to the specific record inside your attributeValues array, therefore, when you do this.attributeValues.splice() , it can't find your attributeValues object property. So, shift the function into the attributeValueViewModel object and use self instead of this , like so:

//This is inside function attributeValueViewModel(data)
self.removeAttributeValue = function() {
    alert(JSON.stringify(this));
    self.attributeValues.splice(this.id, 1);
}

To call it, just change your data-bind code to use $parent instead of $root , like so:

<button data-bind="click: $parent.removeAttributeValue">REMOVE</button>

Something like this fiddle here: http://jsfiddle.net/UMB79/

(Note that with these changes you still have to modify your logic to correctly add/remove elements, 'cause it's still buggy)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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