Knockout.js用单个json对象绑定一个observable

时间:2015-02-16 18:11:57

标签: javascript asp.net json knockout.js asp.net-web-api

我试图对具有单个json对象的observable进行数据绑定。我可以用ko.observablearray做这个没有foreach的问题,但不知道如何使用observale

这是我的观点模型

var ViewModel = function () {
    var self = this;
    self.job = ko.observable();
}

self.job已经填充了来自api调用的json对象,这可以正常但我不知道如何数据绑定到html。我试过了foreach

<p data-bind="foreach: job">
Name: <span data-bind="text: jobslist.Name"> </span>
Description: <span data-bind="text: jobslist.Description"> </span>
</p>

它不会给出任何错误空白

{
    "JobID":1,
    "JobsListID":1,
    "BookingID":2,
    "TimeAllowed":20,
    "TimeTaken":22,
    "Comments":"Some comments",
    "Status":"complete",
    "Notes":null,
    "TimeStarted":"2014-11-04T09:00:00",
    "Difficulty":1,
    "CompleteDate":"2014-11-04T09:22:00",
    "booking":null,
    "jobs_mechanics":[],
    "jobslist": {
        "JobsListID":1,
        "JobCategoryID":1,
        "Description":"Change Tyres                  ",
        "Name":"Tyres",
        "jobs":[],
        "jobscategory":null,
        "model_jobslist":[]
     },
     "timessheets":[]
}

1 个答案:

答案 0 :(得分:1)

您应该能够使用with绑定获得结果。以下是假设您使用局部变量而不是Web服务调用的代码:

var data = {
    "JobID":1,
    "JobsListID":1,
    "BookingID":2,
    "TimeAllowed":20,
    "TimeTaken":22,
    "Comments":"Some comments",
    "Status":"complete",
    "Notes":null,
    "TimeStarted":"2014-11-04T09:00:00",
    "Difficulty":1,
    "CompleteDate":"2014-11-04T09:22:00",
    "booking":null,
    "jobs_mechanics":[],
    "jobslist": {
        "JobsListID":1,
        "JobCategoryID":1,
        "Description":"Change Tyres                  ",
        "Name":"Tyres",
        "jobs":[],
        "jobscategory":null,
        "model_jobslist":[]
     }, 
     "timessheets":[]
};
var ViewModel = function () {
    var self = this;
    self.job = ko.observable(data);
}
var vm = new ViewModel();
ko.applyBindings(vm);

和HTML:

<p data-bind="with: job().jobslist">
Name: <span data-bind="text: Name"> </span>
Description: <span data-bind="text: Description"> </span>
</p>

这是jsFiddle