there's several similar questions accessing nested json in knockout, can't work. i'm sure it's simple. i'd without knockout.mapping plugin if possible.
edit:
here's fiddle put together. https://jsfiddle.net/ym0h4w49/14/
i can't render dom on site i'm working on, console.log shows singlecontact object. uncomment self.tags see how breaks.
given json response nested objects:
{ "id": 1, "firstname": "ina", "lastname": "church", ... etc ... "registered": "2014-10-06t11:22:51 +05:00", "tags": [ { "id": "t1", "contactid": 1, "taglabel": "wguldin" } ] } how access tags person? i've tried following.
function detailviewmodel(contactid) { var self = this; self.contactid = ko.observable(contactid); self.contact = ko.observablearray([]); self.getcontact = function(id) { $.ajax({ type: 'get', url: 'http://localhost:3000/contacts/' + id + '?_embed=tags&_embed=reminders', datatype: 'json', success: function(data) { var contactdata = new singlecontact(data); self.contact(contactdata); } }); } self.getcontact(self.contactid()); }; this view model creates new singlecontact, processes data so:
function singlecontact(data) { var self = this; self.firstname = data.firstname; self.lastname = data.lastname; ... self.tags = ko.observablearray(ko.utils.arraymap(self.tags, function(tag) { return new tag(tag.id, tag.contactid, tag.taglabel); })); }; which should pass in tag information function, think.
function tag(id, contactid, taglabel) { var self = this; self.id = id; self.contactid = contactid; self.taglabel = taglabel; } but when console.log singlecontact, weird function thing appears tags value.

i'm not sure if means there or not, doesn't render in dom using markup:
<!-- ko foreach: contact --> <h1 data-bind="text: firstname"></h1> ... <!-- ko foreach: tags --> <p data-bind="text: tag.taglabel"></p> <!-- /ko --> <!-- /ko --> thanks!
try
view:
<!-- ko foreach: contact --> <h1 data-bind="text: firstname"></h1> <!-- ko foreach: tags --> <p data-bind="text:taglabel"></p> <!-- /ko --> <!-- /ko --> viewmodel:
var json = { "id": 1, "firstname": "ina", "lastname": "church", "registered": "2014-10-06t11:22:51 +05:00", "tags": [ { "id": "t1", "contactid": 1, "taglabel": "wguldin" } ] } function tag(id, contactid, taglabel) { var self = this; self.id = id; self.contactid = contactid; self.taglabel = taglabel; } function singlecontact(data) { var self = this; self.firstname = data.firstname; self.lastname = data.lastname; var con = ko.utils.arraymap(data.tags, function(item) { // use item rather tag may give different meaning & loop through data.tags return new tag(item.id, item.contactid, item.taglabel); }); self.tags = ko.observablearray(con); }; function detailviewmodel() { var self = this; self.contact = ko.observablearray([]); self.contact([new singlecontact(json)]); // use [] here make array }; ko.applybindings(new detailviewmodel()) sample working fiddle here
check here working fiddle sample
Comments
Post a Comment