0

我有一个 viewModel 有这个 observableArray

(function () {
    function myItems() {
        var self = this;
        self.itemArray = ko.observableArray();
        somefunction() {...
}
var myViewModel = new myItems();

这个 observableArray 将包含这样的实例:

(function () {
    function item() {
        var self = this;
        self.name = ko.observable("some data");
        self.doStuff = function () {
            return "doing whatever";
        };
    }
    window.item = item
}());

我将我的 json 映射到 viewModel

var json = '{"name":"my main property", "itemArray": [ { "name": "Bob" }, { "name" : "Fred" } ] }';

var myViewModel = new myItems();
ko.mapping.fromJSON(state, {}, myViewModel);

如何告诉映射它必须使用 item 对象映射 itemArray?如何在 item() 和 myItems() 之间创建链接?

这是一个显示问题的小提琴 http://jsfiddle.net/dexster/hLEMz/7/

4

2 回答 2

1

解决方案是使用映射选项的创建回调

var mapping = {
    'itemArray': {
        create: function (options) {
            //add items to the items object here
            ...
于 2013-04-18T07:29:39.043 回答
0

Well, once you've serialised it into JSON to store the state, you're back to the position you were in before you processed the JSON data to populate your view models in the first place.

Actually, that's the first issue you have, you are serialising the new viewmodel, if you serialise itemArray on the viewmodel, then you will have the data that you started with:

var unmapped = ko.mapping.toJSON(myViewModel1.itemArray);

Then, you can just pass that in to your addItems method:

myViewModel2.addItems(unmapped);

instead of mapping them.

Here's an updated jsFiddle

于 2013-04-17T19:01:14.813 回答