How do you observe JavaScript hosting in Knockout?

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("&") : ""; }); 
+6
source share
1 answer

See the second example on the observed array page. Just create an array of key / value pairs:

 // This observable array initially contains three objects var anotherObservableArray = ko.observableArray([ { name: "Bungle", type: "Bear" }, { name: "George", type: "Hippo" }, { name: "Zippy", type: "Unknown" } ]); 

In your examples, you only iterate (except delete), so there is no real need to use a real dictionary. It would be simple enough to find the key. I think that using the map is to some extent a premature optimization. It also does not fully match the ability of query strings to support the same key multiple times.

Edit: if you want to observe a change in the key or value in this example, you also need to make these properties visible:

 var anotherObservableArray = ko.observableArray([ { name: ko.observable("Bungle"), type: ko.observable("Bear") } ]); 
+7
source

Source: https://habr.com/ru/post/912803/


All Articles