Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a computed observable array in Knockout

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 
like image 932
Matt Mangold Avatar asked Jul 02 '12 18:07

Matt Mangold


People also ask

How do I set observable value in Knockout?

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.

Which function is used for computation in Knockout?

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.

What is observable array in knockout JS?

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.

How do I sort Knockout observable array?

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.


2 Answers

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); 
like image 132
Brian S Avatar answered Oct 01 '22 20:10

Brian S


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.

like image 39
tne Avatar answered Oct 01 '22 20:10

tne