淘汰赛 ko.mappings.fromJS 无效

Knockout ko.mappings.fromJS not working

我正在尝试使用敲除映射,但它没有像我预期的那样工作。 在这里,我创建了最简单的 fiddle,但它不起作用。

我是不是漏掉了什么?

https://jsfiddle.net/p48d11j5/1/

function Model(){
    var self = this;

    self.Id = ko.observable(0);
    self.Name = ko.observable("Default");
    self.Visible = ko.observable(false);
    self.Items = ko.observableArray([]);
}

function ModelItem(){
    var self = this;

    self.Id = ko.observable(0);
    self.Name = ko.observable("Default item name")
}

var m = new Model();

ko.mapping.fromJS({
    Id:1,
    Name: "Test",
    Visible: true,
    Items: [
    {
        Id:1,
        Name:"First"
    },
    {
        Id:2,
        Name:"Second"
    }
  ]
}, m);

ko.applyBindings(m);

编辑:我正在使用嵌套数组,所以我添加了数组

edit2:我想要模型 "typed" 使用函数或它们的 ko.computed 属性

您可以试一试,使用映射插件设置默认状态并应用更新:

// Set up the initial model.
var model = ko.mapping.fromJS({
    Id: 0,
    Name: "Default",
    Visible: false,
    Items: []
});

ko.applyBindings(model);

// Map new data from the "server"...
var model = ko.mapping.fromJS({
    Id:1,
    Name: "Test",
    Visible: true,
    Items: [
    {
        Id:1,
        Name:"First"
    },
    {
        Id:2,
        Name:"Second"
    }
    ]
}, model);

// ...or directly manipulate the model.
model.Id(2);
model.Items.push({Id: 3, Name: "Third"});

https://jsfiddle.net/3evtx022/

试试这个

var m = ko.mapping.fromJS({
    Id:1,
  Name: "Test",
  Visible: true,
  Items: [
    {
        Id:1,
      Name:"First"
    },
    {
        Id:2,
      Name:"Second"
    }
  ]
}, new Model());

ko.applyBindings(m);

工作示例:https://jsfiddle.net/p48d11j5/2/

如果你用两个参数调用 ko.mapping.fromJS :
ko.mapping.fromJS(data, mappedObject) 第二个参数是 mappedObject 已经是 created.Then 第二个参数将是被视为 viewModel 而不是 options

您所要做的就是:ko.mapping.fromJS(data, {}, viewModel) - 这会将您的数据放入模型中。

ko.mapping.fromJS({
    Id:1,
    Name: "Test",
    Visible: true,
    Items: [{Id: 1, Name: "First"}, {Id: 2, Name: "Second"}]
  }, {} ,m);  // pass the second argument as an empty object.