javascript - knockoutjs mapping custom objects with nesting array -
i want map json custom objects. problem items not typeof item object normal objects. i'm missing here?
you can test here: http://jsfiddle.net/5jhpe/
var json = [ { id: 1, items: [ {id: 1, name: 'item1'}, {id: 2, name: 'item2'}, {id: 3, name: 'item3'} ] }, { id: 2, items: [ {id: 4, name: 'item4'}, {id: 5, name: 'item5'}, {id: 6, name: 'item6'} ] }, ] function data(data) { ko.mapping.fromjs(data, {}, this); } function item(data) { ko.mapping.fromjs(data, {}, this); } var map = { create: function(options) { return new data(options.data); }, items: function(options) { return new item(options.data); }, } var res = ko.mapping.fromjs(json, map);
output:
console.log(res()); [data, data] -- console.log(res()[0].items()); [object, object, object] <-- here want have [item, item, item]
i've changed mapper options in way
var map = { 'items': { create: function(options) { return new item(options.data); } } }
and seems fine; try?
if need: jsfiddle console output [item, item, item] want;
i permit add 1 little suggestion: if need test typeof in way:
typeof res()[0].items()[0]
pay attention, tricky!
to avoid problem, declare item viewmodel in way:
function item(data) { var self = this; self.mytype = 'item'; ko.mapping.fromjs(data, {}, this); }
so can test, example :
if('item' === res()[0].items()[0].mytype) { //do something... }
this "mytype" trick suggests here in stackoverflow time ago: i'll post link here i'll find post
Comments
Post a Comment