将嵌套的JSON绑定到Knockout View Model

时间:2014-06-10 13:24:09

标签: javascript json knockout.js

我正在尝试从表示二维数组的JSON字符串绑定KnockoutJS视图模型。但是我遇到的问题是只显示数组的第一级。

我的模型看起来像这样:

function CategoriesModel(categories) {
    var self = this;

    self.categories = ko.observableArray(ko.utils.arrayMap(categories, function (category) {
        return {
            description: category.description,
            checks: ko.observableArray(category.checks)
        };
    }));

    self.addCategory = function () {
        self.categories.push({
            description: "",
            checks: ko.observableArray()
        });
    };

    self.removeCategory = function (category) {
        self.categories.remove(category);
    };

    self.addCheck = function (category) {
        category.checks.push({
            description: "",
            keypoint: "",
            penaltypoints: ""
        });
    };

    self.removeCheck = function (check) {
        $.each(self.categories(), function () {
            this.checks.remove(check)
        });
    };

    self.save = function () {
        self.lastSavedJson(JSON.stringify(ko.toJS(self.categories), null, 2));
    };

    self.lastSavedJson = ko.observable("");
};

我尝试绑定JSON数据的方法是:

function loadData() {
    var rawJSON = '[
        {
            "description":"01", 
            "checks":{"
                    description":"01", 
                    "keypoint":"01", 
                    "penaltypoints":"01"
            }
        },{
            "description":"02", 
            "checks":{
                    "description":"02", 
                    "keypoint":"02", 
                    "penaltypoints":"02"
            }
        }
    ]';

    var parsedJSON = JSON.parse(rawJSON);

    viewModel.categories = ko.mapping.fromJSON(rawJSON);

    ko.applyBindings(viewModel);
}

有谁能告诉我我的错误是什么?任何帮助将不胜感激。

编辑: 我试图创建一个jsfiddle(http://jsfiddle.net/EAu2E/4/),但似乎knockout.js和knockout-mapping.js资源没有正确加载。

1 个答案:

答案 0 :(得分:0)

问题出在JSON字符串中。虽然http://jsonlint.com显示以下字符串为有效:

var rawJSON = '[
    {
        "description":"01", 
        "checks":{"
                description":"01", 
                "keypoint":"01", 
                "penaltypoints":"01"
        }
    },{
        "description":"02", 
        "checks":{
                "description":"02", 
                "keypoint":"02", 
                "penaltypoints":"02"
        }
    }
]';

Knockout JS期待嵌套列表周围的方括号(也是有效的JSON),如下所示:

var rawJSON = '[
    {
        "description":"01", 
        "checks":[{"  //<----- Square bracket required here.
                description":"01", 
                "keypoint":"01", 
                "penaltypoints":"01"
        }]  //<----- Square bracket required here.
    },{
        "description":"02", 
        "checks":[{  //<----- Square bracket required here.
                "description":"02", 
                "keypoint":"02", 
                "penaltypoints":"02"
        }]  //<------ Square bracket required here.
    }
]';