Magento – How to make observable array in knockout js model and bind it to html via view js in magento2

knockoutmagento2

I want to make one observable array in knockout js model and this array need updating on click event:

That is what I have tried:

js/model/test.js

var testArray = ko.observableArray();

test : function(){
testArrayy()[0]=true;
testArray()[1]=false;

}

Now in js/view/test.js

I have made a test variable: test.test; and bind it with test.html:

<div data-bind:"visible:test.[0]:>test0 div</div>

But it's not working.

Does anyone know how to observe array through model and bind it via view js

All other logic I already know. I have just written pseudo for a basic idea here.

My main question is:
How to bind observable array using key and value in Magento 2?

let me give me example what i want actually to do:

INDIA
GUJARAT(visible if click on india)
RAJKOT(visible if click on gujarat)
GONDAL(visible if click on gondal)
AMERICA

there are many options which we need to visible on click

it's just a simple example

Best Answer

In your model file declare a variable like this.

define(['ko'], function(ko) {
    'use strict';
    var array1 = ko.observable([]);
    var array2 = ko.observable([]);
    return {
        array1: array1,
        array2: array2,
    };
});

and in view/test.js file

define(
        [
            'jquery',
            'ko',
            'uiComponent',
            'Vendor_Module/js/model/test'
        ],
        function($, ko, Component,mytest) {
           mytest.array1(['your multidiamation array here']);

});

Hope it will help you.

UPDATE:

https://inviqa.com/blog/using-knockout-js-magento-2

Related Topic