I have a nested json i eventually broke down to use with ko.mapping
:
{ users: [ { k: 'key',
name: 'Alice'
},
],
roles: [ { k: 'key',
name: 'Standard',
regex: [ ( 'root', 'me', 'myself'),
],
},
]
}
...etc.
My situation is that:
- my UI needs a data-bind on vm.users.k, but json data (via
$.getJSON
or$.ajax
) is not jet loaded from server; - how can I define the UI, binding a dom element to e.g.
vm.users.name
, while waiting for ajax request to succeed?
I was looking at this question but maybe I miss the point.
My goal is to define the UI without modeling the initial viewModel, letting it be populated by an Ajax call to server. All nested items and array are needed to became observables.
My last code after some iterations:
function ViewModel( ) {
var self = this;
self.users = ko.observableArray();
self.roles = ko.observableArray();
// etc. logic
};
var viewModel = new ViewModel();
ko.applyBindings( viewModel );
$.getJSON('/api/call/from/server', function( data ){
ko.mapping.fromJS( data.users, {}, viewModel.clienti );
ko.mapping.fromJS( data.roles, {}, viewModel.procedure );
});
And html:
<select name="users" data-bind="options: users,
optionsCaption: '',
optionsText: name,
optionsValue: k">
Server side google app engine with headers:
self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
self.response.out.write( json.dumps( object ) )
Actually, I don't want to use async: false
.
I managed to broke ko.mapping
invocation in three calls from js data.responseJSON
, e.g. mapping users to vm.users, then roles to vm.roles, etc.