Harry
Harry

Reputation: 621

Knockout.js Cannot read properties of undefined inside ViewModel

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>

Upvotes: 1

Views: 565

Answers (1)

Nathan Fisher
Nathan Fisher

Reputation: 7941

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>

Upvotes: 2

Related Questions