I would like to know how to create a computed observable array.
In my view model, I have 2 observable arrays, and I would like to have a computed observable array that is simply both arrays combined.
function ViewModel() { var self = this; self.listA= ko.observableArray([]); self.listB = ko.observableArray([]); self.masterList= //combine both list A and B
To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.
In some scenarios, it is useful to programmatically determine if you are dealing with a computed observable. Knockout provides a utility function, ko. isComputed to help with this situation. For example, you might want to exclude computed observables from data that you are sending back to the server.
If you want to detect and respond to changes of a collection of things, use an observableArray . This is useful in many scenarios where you're displaying or editing multiple values and need repeated sections of UI to appear and disappear as items are added and removed.
Description. The KnockoutJS Observable sort() method sorts all items in the array. By default, items are sorted in an ascending order. For sorting an array in a descending order, use reverse() method on sorted array.
This will combine the two arrays and return the combined list. However, it is not a computed observable array (don't know if that is even possible), but a regular computed observable.
self.masterList = ko.computed(function() { return this.listA().concat(this.listB()); }, this);
self.masterList = ko.observableArray(); ko.computed(function () { self.masterList(self.listA().concat(self.listB())); });
Similar to Joe Flateau's answer in spirit, but I like to think this method is simpler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With