我在根级别有一个Calendar
的模型。此Calendar
包含许多days
,每个Day
包含Event
,每个Event
包含attendees
,每个Attendee
包含0或更多Intolerance
s。
所以它看起来像这样:
function Calendar(data) {
this.days = ko.observableArray(data.days);
}
function Day(data) {
this.date = ko.observable(data.date);
this.event = ko.observable(data.event);
this.daysToEvent = ko.computed(function () {
var diff = Math.abs(new Date(), this.date());
return (((diff / 1000) / 60) / 60) / 24;
}, this);
}
function Event(data) {
this.name = ko.observable(data.name);
this.attendees = ko.observableArray(data.attendees);
}
function Attendee(data) {
this.name = ko.observable(data.name);
this.age = ko.observable(data.age);
this.intolerances = ko.observable(data.intolerances);
}
function Intolerance() {
this.id = ko.observable(data.id);
}
我正在将JSON字符串传递给此模型,并使用ko.mapping
插件(刚开始使用它)将其全部连接起来。我不理解的是,我如何告诉插件在映射期间使用我的对象?
我知道映射选项参数,但目前我是一个新手,所以不是真的“得到它”可以这么说。我试过这个:
var viewModel = {
calendar: null,
loadCalendar: function () {
ko.mapping.fromJSON(json, {
create: function (opts) {
return new Calendar({ days: opts.data.calendar })
}
}, viewModel.calendar);
}
};
哪个获取我的Calendar
对象和日期,但是如何(以及最正确方式)是什么?我还要将我的课程映射到树下?
答案 0 :(得分:1)
您可以将映射代码放在ViewModels中:
function Calendar(data) {
this.days = ko.observableArray();
// update the current ViewModel with the given data
if (data) {
ko.mapping.fromJS(data, {
days: {
// tell the mapping plugin how to create the days
create: function(options) {
return new Day(options.data);
}
}
}, this);
}
}
function Day(data) {
this.date = ko.observable();
this.event = ko.observable();
if (data) {
ko.mapping.fromJS(data, {
event: {
create: function(options) {
return new Event(options.data);
}
}
}, this);
}
this.daysToEvent = ko.computed(function () {
var diff = Math.abs(new Date(), this.date());
return (((diff / 1000) / 60) / 60) / 24;
}, this);
}
...