Knockout.js Make every nested object an Observable

后端 未结 6 1717
轻奢々
轻奢々 2020-12-04 22:00

I am using Knockout.js as a MVVM library to bind my data to some pages. I\'m currently building a library to make REST calls to a web service. My RESTful web service returns

6条回答
  •  抹茶落季
    2020-12-04 22:34

    From what I have experienced, ko.mapping.fromJS does not make an observable out of an object.

    Let's say you have this ViewModel constructor:

    var VM = function(payload) {
      ko.mapping.fromJS(payload, {}, this);
    }
    

    and this data object:

    var data1 = {
      name: 'Bob',
      class: {
        name: 'CompSci 101',
        room: 112
      }
    

    }

    and you use data1 to create VM1:

    var VM1 = new VM(data1);
    

    Then VM1.class will not be a ko.observable, it is a plain javascript Object.

    If you then create another viewmodel using a data object with a null class member, ie:

    var data2 = {
      name: 'Bob',
      class: null
    }
    var VM2 = new VM(data2);
    

    then VM2.class is a ko.observable.

    If you then execute:

    ko.mapping(data1, {}, VM2)
    

    then VM2.class remains a ko.observable.

    So, if you create a ViewModel from a seed data object where object members are null, and then popuplate them with a populated data object, you will have observable class members.

    This leads to problems, because sometimes the object members are observables, and sometimes they are not. Form bindings will work with VM1 and not work with VM2. It would be nice if ko.mapping.fromJS always made everything a ko.observable so it was consistent?

提交回复
热议问题