0
votes

I am trying to change the flag value of an item of the complex object. Object structure is:

modelData 
    [0]: 
        Main: xz1
        Sub: a,b,c,d,e
        show: true
    [1]:
        Main: xs1
        Sub: g,h,i,j,k
        show: false

I need to access this object and toggle the flag value, if it is true i have to change this as false, if false means i have to make this as true.

Code I tried

toggleShow: function (item) {
          var index = modelData.indexOf(item);
          modelData[index].show = item.show ? false : true; // should get work but not :(
}

item data inside function is,

item
{...}
    __proto__: {...}
    Main: "AXD"
    Sub: [ fg,jk,ik,ko]
    show: true

modelData is an observable Array.

modelData
function observable() {
        if (arguments.length > 0) {
            // Write

            // Ignore writes if the value hasn't changed
            if (observable.isDifferent(_latestValue, arguments[0])) {
                observable.valueWillMutat
    [Methods]: {...}
    __proto__: {...}
    _id: 168
    _latestValue: [[object Object]]
    _subscriptions: {...}
    arguments: null
    caller: null
    length: 0
    prototype: {...}

By using that _latestValue i can fetch the object content.

modelData._latestValue
[[object Object]]
    __proto__: []
    length: 1
    [0]: {...}

but I could not access this using index. Please tell me where my things getting wrong and why i could not access the value using index of the element.

EDIT:

Now I can toggle the flag value. But once the flag value updated my list in view not getting updated. Please find my fiddle here Output:

+ Main1
    hello
    hi
+ Main2
    one
    two

if I click that plus symbol then sub list should get hide. if i again click that plus symbol it should show the sub list again.

Any suggestion would be helpful.

1

1 Answers

3
votes

You have to unwrap your observableArray to get the underlying array with calling modelData as a function with no arguments.

So you need to add the () before the [index]:

toggleShow: function (item) {
          var index = modelData.indexOf(item);
          modelData()[index].show = item.show ? false : true; 
}

Note: the indexOf is working without the () because it is implemented additionally for the observableArray but the indexer is not.

In order to see the changes on the UI you have to convert your show property a ko.observable, and you need to updated it with:

toggleShow: function (item) {
          var index = modelData.indexOf(item);
          modelData()[index].show(item.show() ? false : true); 
}

Your updated code: https://jsfiddle.net/ujs77n7r/