1

I have an object inside the viewModel where the "visible" property will have the value of the loadingVisible variable declared inside the viewModel as an observable.

My problem is that I always get the following error: Cannot read properties of undefined (reading 'loadingVisible');

I've tried in several ways but I still have the same error, is there any solution?

  var viewModel = {
        loadingVisible: ko.observable(false),
        loadOptions: {
            visible: viewModel.loadingVisible(),
            showIndicator: true,
            showPane: true,
            shading: true,
            hideOnOutsideClick: false,
            shadingColor: 'rgba(0,0,0,0.4)',
        },
  };

    return viewModel;

HTML

<div class="loadpanel" data-bind="dxLoadPanel: loadOptions"></div>
Harry
  • 621
  • 3
  • 9
  • 21
  • 1
    Does this answer your question? [Self-references in object literals / initializers](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers) – Dorad Jul 14 '22 at 12:20

1 Answers1

2

Easiest way I know is to have a property that both things can reference.

var loadingVisible = ko.observable(false);
var viewModel = {
        loadingVisible: loadingVisible,
        loadOptions: {
            visible: loadingVisible,
            showIndicator: true,
            showPane: true,
            shading: true,
            hideOnOutsideClick: false,
            shadingColor: 'rgba(0,0,0,0.4)',
        },
        toggleVisible: function(){
          loadingVisible(!loadingVisible());
        }
  };

ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div class="loadpanel" data-bind="visible: loadOptions.visible">
 <ul><li>Test</li></ul>
</div>
<button data-bind="click: toggleVisible">Press Me</button>
Nathan Fisher
  • 7,961
  • 3
  • 47
  • 68