I’m totally stuck.
Given a static observable array:
obj.allRoles = ko.observableArray([
new Role(1, "Adminx"),
new Role(2, "Temp2x"),
new Role(3, "Temp3x")
]);
bound to a select
<select data-bind="options: allRoles,
optionsText: 'RoleName',
optionsValue: 'RoleId',
optionsCaption: 'Add a new role...',
value: selectedRole">
</select>
and a function that runs via a click binding:
function addRole() {
alert('got id:' + obj.selectedRole());
var selectedId = obj.selectedRole();
var match = ko.utils.arrayFirst(obj.allRoles(), function (item) {
return item.RoleId == selectedId;
});
alert('got :' + match.RoleName);
return;
}
All is well. The first alert shows obj.SelectedRole() returns the value of a select option
and the second alert shows a match is found and the RoleName is displayed. OK so far.
If I replace the static observable array for one populated from a service, eg:
obj.allRoles = ko.observableArray([]);
and
//data
function loadAllRolesFromSvc() {
var url = '/api/UserSvc/GetAllRoles';
$.getJSON(url,
function (data) {
obj.allRoles.removeAll();
var results = ko.observableArray();
ko.mapping.fromJS(data, {}, results);
for (var i = 0; i < results().length; i++) {
var role = new Role();
role.RoleId = results()[i].RoleId;
role.RoleName = results()[i].RoleName;
obj.allRoles.push(role);
};
}
);
};
Then I see the select populated OK, but when the addRole() function is run the first alert shows that selectedRole is provided with a value, but the code to locate the matching Role object by RoleId (in addRole()) fails – the match is always null.
How can I fix this?
All pointers welcome.
Many Thanks.
I guess that
RoleIdandRoleNameproperties inRoleclass are not observable, but inloadAllRolesFromSvcfunction you set them to be observable.The code
ko.mapping.fromJS(data, {}, results);convers all properties inside results to observableArrays and observables. Really, I don’t understand why are you convert results to observable. So to fix issue you could remove mapping:Or you could unwrap
RoleIdandRoleNamevalues: