Update part of mapped ko model

2019-09-04 17:19发布

How can I just update one part of a mapped model?

var model = { foo: { bar: "hello" }, moo: { la: "world" }};
var mapped = ko.mapping.fromJS(model);

Mapping results in:

mapped =
{
   __ko_mapping_object__ : object,
   foo: {
      bar : function c()
   },
   moo: {
      la: function c()
   },
   __proto__ : object

}

Since foo and moo aren't observable, if I do:

mapped.foo = { "bar" : "changed" };

or

mapped.foo = ko.mapping.fromJS({ "bar" : "changed" });

The object is updated but rebinding is not triggered.

Any ideas? I need binding to happen on updating a one part of the model.

One idea I had was to crawl the partial model and then force rebind.

triggerObjectRebind(mapped.foo);

function triggerObjectRebind(model) {
    for (var property in model) {
        if (model.hasOwnProperty(property)) {
            if (typeof model[property] === "object") {
                triggerObjectRebind(model[property]);
            } else if (typeof model[property] === "function") {
                model[property].valueHasMutated();
            }
        }
     }
 }

1条回答
Emotional °昔
2楼-- · 2019-09-04 17:48

When you do updates, you need to pass in the mapped object as a parameter. Corresponding properties will be updated.

var model = {
    foo: { bar: "hello" },
    moo: { la: "world" }
};
var mapped = ko.mapping.fromJS(model);

var newFoo = { bar: "changed" };
// do the update on the foo object
ko.mapping.fromJS(newFoo, {}, mapped.foo);
查看更多
登录 后发表回答