Reputation: 1255
I have a computed observable in my model. It is updatable. It writes first value from select array into user Roles array though reads right value from it, so it's messy. If you try my JSFiddle you will see, that after you choose another value from select another dependents aren't changing. How can I make it work? Thank you!
<div id="UserManagement" class="container">
<div class="col-md-12">
<div data-bind="with: user">
<select data-bind="options: $root.apps, value: app, optionsText: 'name', optionsValue: 'code'"></select>
</div>
<select data-bind="options: apps, value: user().app, optionsText: 'name', optionsValue: 'code'"></select>
<!-- ko foreach: user().roles -->
<input type="text" data-bind="value : $data" />
<!-- /ko -->
</div>
function UserManagementModel() {
var self = this;
self.apps = [{
code: "ROLE_APP1",
name: "App1"
}, {
code: "ROLE_App2",
name: "App2"
}, {
code: "ROLE_MANAGER",
name: "Manager panel"
}];
self.user = ko.observable(new User({
userId: 1,
username: "Nick",
roles: ["ROLE_MANAGER", "ROLE_CHANGE_USER"]
}))}
function User(data) {
var self = this;
self.userId = data.userId;
self.username = ko.observable(data.username);
self.roles = ko.observableArray(data.roles);
self.app = ko.computed({
read: function () {
return ko.utils.arrayFilter(self.roles(), function (value) {
return value.indexOf('_', value.indexOf('_') + 2) < 0;
})[0];
},
write: function (value) {
$.each(self.roles(), function (indx, role) {
if (role.indexOf('_', role.indexOf('_') + 1) < 0) self.roles()[indx] = value;
});
},
owner: self
}).extend({
throttle: 50
});}
var model = new UserManagementModel();ko.applyBindings(model);
Upvotes: 0
Views: 47
Reputation: 8487
@Skeeve its not clear to me what you are try to achieve but the reason why your computed observable (app) is not evaluating is because :
The dependency of your computed observable (app) is roles observable array and in its write function you are updating the value (not array) of the observable array which itself is not observable so knockout didn't find any change in observable array because of this its read function is not executing
So if you want to evaluate computed observable (app) on roles array value change then you have to create each value observable in roles observable array, in your case you can do this:
...
roles: [
ko.observable("ROLE_MANAGER"),
ko.observable("ROLE_CHANGE_USER")]
..
Upvotes: 1