MojoDK
MojoDK

Reputation: 4528

Bind knockoutjs to javascript object property

I'm new to Knockoutjs, so please bear with me.

I want to knocoutjs bind a DxForm (DevExpress) to an javascript object property, but I get an error ... "Cannot read property 'items' of undefined".

I am uncertain if this is a knockout problem, DevExpress problem or just incufficient coding skills from my part.

Here's my code...

HTML:

<div data-bind="dxForm: frm.options"></div>

Javascript:

var viewModel = function() {
    var that = this;

    // -----------------------------------------------------------------
    // Faste...
    // -----------------------------------------------------------------
    that.frm = {
       items: ko.observable(undefined),
       data: ko.observable(undefined),
       instance: ko.observable({}),
       options: {
          items: that.frm.items,
          formData: that.frm.data,
          onInitialized: function(e) {
             that.frm.instance(e.component);
          },
       },
    };

    return {
       frm: that.frm,
    };

 };

 var vm = new viewModel();
 ko.applyBindings(vm);

 var items = [{
    "dataField": "test",
    "editorOptions": {
       "type": "date",
       "pickerType": "calendar",
    },
    "editorType": "dxDateBox",
    "name": "Test",
    "visible": true
 }];

 var data = {
    test: 10,
 };

 vm.frm.data(data);
 vm.frm.items(items);

JSFiddle: https://jsfiddle.net/MojoDK/ke395v2c/3/

I want to bind to objects since I'm going to use several DxForm objects and I like to keep the code to each DxForm in an object (easier to read).

Any idea why it fails?

Thanks.

Upvotes: 1

Views: 196

Answers (1)

OrcusZ
OrcusZ

Reputation: 3660

You just have a problem with closure in your frm.

The that property in frm object do not exist you should use this...

But in your onInitialized function, this and that will not target your viewModel object...

So this way, the easiest is to declare options object later :

 that.frm = {
       items: ko.observable(undefined),
       data: ko.observable(undefined),
       instance: ko.observable({})
    };

         that.frm.options = {
          items: that.frm.items,
          formData: that.frm.data,
          onInitialized: function(e) {
             that.frm.instance(e.component);
          },
       };

Updated jsfiddle

Upvotes: 2

Related Questions