你可以像下面這樣做(小提琴不鍍鉻工作)
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));
這是完美的。並感謝您對可觀察的反饋。我確實有其他變化的東西,我剛剛剝離了我的例子。 – user2421464
不客氣 – Damien