I am using a Knockout computed observable to store data from my users in the following fashion:
var DummyClass = (function() {
userPrefs = ko.observable({
value1: 0,
value2: 0,
value3: 0});
commonPrefs = ko.observable({
required: false
});
var userSettings = ko.computed(function() {
var value1 = userPrefs().value1;
var value2 = userPrefs().value2;
var value3 = userPrefs().value3;
if (typeof value1 === 'undefined') {
value1 = 0;
}
value1 = String(value1);
if (value1.length === 0) {
if (commonPrefs().required === true) {
value2 = 0;
value3 = 1;
}
else {
value2 = 1;
value3 = 0;
}
}
return {
value1: value1,
value2: value2,
value3: value3
};
}
}
If I retrieve value1 by using dummyClass.userSettings().value1 elsewhere in my code, or update it with new values, any further attempts to update the data stored in userSettings via dummyClass.userSettings({value1: 1,value2: 2,value3: 3}) (for example) will no longer work, and whatever values I have in userSettings will remain that way unless I reload my web application.
A couple of points:
userPrefs
is observable, but its properties are not. So KO will not know whether they have been changed. One thing to remember with KO is you have to make everything explicitly observable. Though in this case, if you're always updating the entire object, you would get away with that.typeof value1 = 'undefined'
is an assignment and not a comparison, so that won't work.Here's some example code that does what you're looking for (I think):
Fiddle: https://jsfiddle.net/thebluenile/fqznpexg/
But the writable computed isn't really necessary, because you could just manipulate
userPrefs
directly:vm.userPrefs({ value1: 1, value2: 2, value3: 3})
.