与Knockout JS的数据绑定无法正常工作

时间:2015-09-08 09:13:55

标签: javascript jquery json knockout.js

我试图将我的JSON对象绑定到HTML div但是没有任何绑定似乎有效。这是我目前对这个问题的尝试。但我已经尝试过使用模板绑定。这导致了一个未定义的错误,但是对象被正确加载,因为我总是在控制台中得到它。

$(document).ready(function () {
var submissionViewModel = new SubmissionModel();
submissionViewModel.getSubmission().done(function () {
    ko.applyBindings(submissionViewModel, document.getElementById("submission"));
})
});

var SubmissionModel = function () {
var self = this;
//self.loading = ko.observableArray();
self.Submission = ko.observable(null);

self.getSubmission = function () {
    // Let loading indicator know that there's a new loading task that ought to complete
    //self.loading.push(true);

    return $.getJSON('/Submission/GetSubmission',
        function (data) {
            console.log("submission loading")
            console.dir(data);

            self.Submission = ko.mapping.fromJSON(JSON.stringify(data));
        }
    );
}
}

HTML

<div id="submission" data-bind="with: Submission">
<span data-bind="text: SubmissionTitle"></span>
</div>

JSON

"{"
SubmissionID":"1be87a85-6d95-43aa-ad3c-ffa047b759a5",
"SubmissionTitle":"nog wat sliden",
"SubmissionDescription":"////",
"SubmissionFile":"TESTFILE  ",
"CreatedOn":"2015-09-02T21:10:54.913",
"SubmissionPoolID":"5af408f5-515c-4994-88dd-dbb2e4a242a2",
"SubmissionTypeID":1,
"CreatedBy":"a028a47d-3104-4ea4-8fa6-7abbb2d69bbd
"}"

我一直在咀嚼这个问题几天,但我似乎无法让它发挥作用。你们有没有人能指出我正确的方向?

1 个答案:

答案 0 :(得分:2)

在解码字符串内的对象的java脚本中,您需要使用JSON.parse并确保您的对象以{em>双引号内的双引号的方式构造not

<强>视图模型:

var json = '{"SubmissionID":"1be87a85-6d95-43aa-ad3c-ffa047b759a5","SubmissionTitle":"nogwatsliden","SubmissionDescription":"--","SubmissionFile":"TESTFILE  ","CreatedOn":"2015-09-02T21:10:54.913","SubmissionPoolID":"5af408f5-515c-4994-88dd-dbb2e4a242a2","SubmissionTypeID":1,"CreatedBy":"a028a47d-3104-4ea48fa67abbb2d69bbd"}'
var ViewModel = function () {
    this.Submission = ko.observable();
    this.Submission(ko.mapping.fromJS(JSON.parse(json)));
    //you can also use ko.mapping.fromJSON(json) as jeroen pointed out   
};
ko.applyBindings(new ViewModel());

工作样本 here