你可以这样做(小提琴在 chrome 中不起作用)
http://jsfiddle.net/P9LLL/1/
function ReservationsViewModel(data) {
this.kits = ko.observableArray();
ko.mapping.fromJS(data, {}, this);
}
var jsonDataFromBackend = { kits: [{ itemName: "Item1", defaultQuantity: 10 },{ itemName: "Item2", defaultQuantity: 12 } ] };
ko.applyBindings(new ReservationsViewModel(jsonDataFromBackend));
这将为套件中的每个项目创建一个动态类型。您不能以一种很好的方式向这些添加计算和其他函数,而是这样做
http://jsfiddle.net/P9LLL/2/
function SeatReservation(data) {
ko.mapping.fromJS(data, {}, this);
this.total = ko.computed(function() {
return this.price() * this.defaultQuantity();
}, this);
}
function ReservationsViewModel(data) {
this.kits = ko.observableArray();
var mapping = {
kits: {
create: function(options) {
return new SeatReservation(options.data);
}
}
};
ko.mapping.fromJS(data, mapping, this);
}
var jsonDataFromBackend = { kits: [{ itemName: "Item1", defaultQuantity: 10, price: 2 },{ itemName: "Item2", defaultQuantity: 12, price: 5 } ] };
ko.applyBindings(new ReservationsViewModel(jsonDataFromBackend));