2

I have tried bind json file with knockoutjs into my custom template. But i got this error in browser console:

Uncaught TypeError: Cannot read property 'fromJS' of undefined

How to avoid this error? Here some following script that i have:

view/frontend/web/js/view/main-component.js

define(['jquery','uiComponent','ko'], function($, Component, ko){
  'use strict';
  return Component.extend({
    defaults: {
      template: 'My_Module/index'
    },
    initialize: function(){
      var json = {
        "id": 9,
        "fullName": "John Doe",
        "firstName": "John",
        "lastName": "Doe",
        "referenceNumber": "BUY-08",
        "position": "Buyer",
        "type": "Buyer",
        "telephone": "028 82 240780",
        "email": "m@email.com",
        "departmentId": 3,
        "departmentName": "DEPT B",
        "country": "United Kingdom"
      };

      var viewModel = {};

      function success() {
        viewModel = ko.mapping.fromJS(json);
        ko.applyBindings(viewModel);
      }

      success();
    },
  });
});

view/frontend/web/template/index.html

<div>
  Full Name: <input data-bind="value: fullName" /> <br />
  Ref: <input data-bind="value: reference" /> <br />
  Position: <input data-bind="value: position" /> <br />
  Email: <input data-bind="value: email" /> <br />
  Dept: <input data-bind="value: departmentName" /> <br />
  Country: <input data-bind="value: country" /> <br />
</div>
1

Try adding this._super(); at the top of the initialize function, this will call the parent's initialize method.

Also there is no need to apply your own bindings or setup the view model as Magento have already done so, when I tried to bind the viewModel myself it broke Magento's KO implementation.

I asked a similar question which may help - How to use Knockout JS within Magento 2

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.