In my Knockout view model, I have some properties where I try to make a hash observable. So instead of my knockout code
self.MyHash = {};
Now I use:
self.MyHash = ko.observable({});
In other parts of my code, I am manipulating a hash with statements like this:
// add an entry self.MyHash()["test"] = "My Value"; // remove an entry delete self.MyHash()["test"];
The code works because entries are added and deleted properly. However, changes to the hash table do not seem to be detected in the areas of the code that observe it. For example, this computed observable never starts when I change the hash table:
self.Querystring = ko.computed(function () { var f = []; $.each(self.MyHash(), function (k, v) { f.push(encodeURIComponent(k) + '=' + encodeURIComponent(v)); }); return (f.length > 0) ? f.join("&") : ""; });
I am going to suggest that this is because the observed knockouts must be simple variables (or observable arrays) and that it does not detect the main changes to my hash table.
If so, are there any other options? Why is there no observable Hash type in the knockout?
For what it's worth, my workaround is to have an observable array of keys and a regular JavaScript hash table for finding values. Then I changed my computational method to observe an array of keys, and not another hash table variable that I had before. I just want to make sure that I donβt miss the βRight Wayβ to do this in Knockout.
self.MyHashKeys = ko.observableArray(); self.MyHash = {}; self.Querystring = ko.computed(function () { var f = []; $.each(self.MyHashKeys(), function (index, value) { f.push(encodeURIComponent(value) + '=' + encodeURIComponent(self.MyHash[value])); }); return (f.length > 0) ? f.join("&") : ""; });