Noteout Mapping overwriting computed observations, is this intentional?

Let's say you have a setup like below:

var model = function() {
    this.base = ko.observable("Initial");
    this.dependent = ko.computed(function() {
        return this.base() + ", computed";
    }, this);
};

var vm = new model();

      

At this point vm

there is Object { base: observable(), dependent: dependentObservable() }

(as expected)

But, as soon as I run:

ko.mapping.fromJS({base: "hello", dependent: "hi"}, {}, vm)

      

vm

becomes Object { base: observable(), dependent: "hi", __ko_mapping__: Object }

dependent

is no longer observable, I expected it to remain intact.

Is this intentional? If so, what is the reason for this? Shouldn't the dependent observables be kept outside the display?


The reason for this question is that I am using ko.mapping.toJS () to convert vm

to JavaScript object

(which gives the property dependent

as expected).

Then, after a while, I use ko.mapping.fromJS () as shown above. This combination overwrites the vm

ko.computed () property .


Solutions I could come up with:

  • Explicitly specify dependent

    to be ignored during display.

    ko.mapping.fromJS({base: "hello", dependent: "hi"}, {'ignore': "dependent"]}, vm)
    
          

  • Make it dependent

    writable (namesake only)

    this.dependent = ko.computed({
        read: function() {
            return this.base() + ", computed";
        },
        write: function() {},
        owner: this 
    });
    
          


Miscellaneous. Info

  • The "line" that actually overwrites the dependent function Mergeable () (as far as I understand)
+3


source to share





All Articles