如何用knockoutjs绑定我的json对象,这是我的json:
"{\"Sport\":[{\"Name\":\"nana\",\"Description\":\"lmkmsdqd\",\"EndDate\":\"2012-07-22T00:00:00\"},
{\"Name\":\"sfqsdffqf\",\"Description\":\"lkqjskdlqsd\",\"EndDate\":\"2012-07-22T00:00:00\"}],
\"Music\":[{\,\"Name\":\"nana\",\"Description\":\"lmkmsdqd\",\"EndDate\":\"2012-07-22T00:00:00\"},
{\"Name\":\"sfqsdffqf\",\"Description\":\"lkqjskdlqsd\",\"EndDate\":\"2012-07-22T00:00:00\"}]}"
请建议我如何绑定它!!
答案 0 :(得分:6)
好吧,所以我整理了一个粗略的fiddle来演示一些绑定概念,以及ViewModel构造。我不得不清理你的JSON才能做到这一点。它演示了模板,foreach和文本绑定。如果您还没有这样做,我强烈建议您浏览tutorials on the knockout site。
以下是HTML绑定:
Sports
<ul data-bind="template: { name: 'listingTemplate', foreach: sports}"></ul>
</br>
Music
<ul data-bind="template: { name: 'listingTemplate', foreach: music}"></ul>
<script type="text/html" id="listingTemplate">
<li>
<span data-bind="text: name"></span></br>
<span data-bind="text: description"></span></br>
<span data-bind="text: endDate"></span></br></br>
</li>
</script>
和viewmodels:
var Listing = function(data) {
this.name = ko.observable(data.Name || '');
this.description = ko.observable(data.Description|| '');
this.endDate = ko.observable(data.EndDate|| '');
};
var ViewModel = function(data) {
this.sports = ko.observableArray(
ko.utils.arrayMap(data.Sport, function(i) {return new Listing(i);})
);
this.music = ko.observableArray(
ko.utils.arrayMap(data.Music, function(i) {return new Listing(i);})
);
};