4

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

  • Do you mean Vue.js? – Daniel Sep 26 at 16:38
  • no js/view in magento2 – Kazim Noorani Sep 26 at 16:39
  • did you try something like: <div data-bind="foreach observable_array"> and then within the <div> access the value of your array with this <span data-bind="visible: shouldBeVisible"> assuming thats your array: {shouldBeVisible: true} – Daniel Sep 26 at 16:54
  • actually array not observed on click or may be i dont know proper debugging in KO – Kazim Noorani Sep 26 at 16:58
  • can you explain what you actually want to do? – Rakesh Varma Sep 26 at 17:26
4

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

  • i want to set the array value with key and also it in model js not view – Kazim Noorani Sep 26 at 18:01
  • I think you can not set values directly in model without using view or action – Rakesh Varma Sep 26 at 18:03
  • then how can set template and bind value in template? – Kazim Noorani Sep 26 at 18:17
  • using view files not model. Model is only use to pass data between models or view or action. like registry you can say – Rakesh Varma Sep 26 at 18:18
  • @RakeshVarma Can you please tell how to set array value with specific key 965=>"your multidiamation array here" – Rutvee Sojitra Sep 27 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.