Note that there are some explanatory texts on larger screens.

plurals
  1. POsubscribing an observableArray to a computed
    text
    copied!<p>I have an object that is constructed upon a table row from the database. It has all the properties that are found in that entry plus several ko.computed that are the middle layer between the entry fields and what is displayed. I need them to be able translate foreign keys for some field values. </p> <p>The problem is the following: One of the properties is an ID for a string. I retrieve that ID with the computed. Now in the computed will have a value that looks like this: <em>'option1|option2|option3|option4'</em></p> <p>I want the user to be able to change the options, add new ones or swap them around, but I also need to monitor what the user is doing(at least when he adds, removes or moves one property around). Hence, I have created an observable array that I will bind in a way that would allow me to monitor user's actions. Then the array will subscribe to the computed so it would update the value in the database as well. </p> <p>Some of the code: </p> <pre><code>function Control(field) { var self = this; self.entry = field; // database entry self.choices = ko.observableArray(); self.ctrlType = ko.computed({ read: function () { ... }, write: function (value) { if (value) { ... } }, owner: self }); self.resolvedPropriety = ko.computed({ read: function () { if (self.ctrlType()) { var options = str.split('|'); self.choices(createObservablesFromArrayElements(options)); return str; } else { return ''; } }, write: function (value) { if (value === '') { //delete entry } else { //modify entry } }, deferEvaluation: true, owner: self }); self.choices.subscribe(function (newValue) { if (newValue.length !== 0) { var newStr = ''; $.each(newValue, function (id, el) { newStr += el.name() + '|'; }); newStr = newStr.substring(0, newStr.lastIndexOf("|")); if (self.resolvedPropriety.peek() !== newStr) { self.resolvedPropriety(newStr); } } }); self.addChoice = function () { //user added an option self.choices.push({ name: ko.observable('new choice') }); }; self.removeChoice = function (data) { //user removed an option if (data) { self.choices.remove(data); } }; ... } </code></pre> <p>This combination works, but not as I want to. It is a cyclic behavior and it triggers too many times. This is giving some overload on the user's actions because there are a lot of requests to the database.</p> <p>What am I missing? Or is there a better way of doing it? </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload