I am new to KnockoutJS and am curious to see if this is possible. I am trying to wrap a local storage object in a writeable computed so that I can take advantage of the auto-binding goodness of KnockoutJS. However, the "read" operation doesn't reference any observables - consequently the initial value never gets updated:
<select data-bind="foreach: logLevelsArray, value: currentLogLevel">
<option data-bind="attr: { value: $index() }, text: $data"></option>
</select>
_.extend(DevUtilitiesViewModel.prototype, {
...
logLevelsArray: ['error', 'warning', 'info', 'debug'],
currentLogLevel: ko.computed({
read: function() {
return localStorage.getItem("logger-level");
},
write: function( newValue ) {
localStorage.setItem("logger-level", newValue);
}
})
...
});
DevUtilitiesViewModel.currentLogLevel(); // 2 (default)
DevUtilitiesViewModel.currentLogLevel(4);
localStorage.getItem("logger-level"); // 4 - write was successful
DevUtilitiesViewModel.currentLogLevel(); // 2 - still the original value
I understand that this is the expected behavior and I understand why. I also understand that I can make currentLogLevel
a simple observable and subscribe to it and update the local storage that way. But then I have to keep track of the subscription and dispose of it manually, write more code, and so forth. I'm just trying to see if there is a way to do what I am trying to do: provide an observable getter/setter for local storage.