I have a problem with knockoutJS i can't figure out
I have two observableArrays; One containing all available items and one containing all selected items.
How can i return a new array, that contains all the available items ( with all the selected items removed from it)?
The slice function is the observableArray equivalent of the native JavaScript slice function (i.e., it returns the entries of your array from a given start index up to a given end index). Calling myObservableArray. slice(...) is equivalent to calling the same method on the underlying array (i.e., myObservableArray().
To clear an observableArray you can set the value equal to an empty array.
To trigger an element deletion, simply send an event on the subject: this. deleteSubject. next({op:'delete', id: '1'});
I'd use .filter
or ko.utils.arrayFilter
, and .indexOf
or equivalent:
this.remainingOptions = ko.computed(function(){
return this.availableOptions().filter(function(option) {
return this.selectedOptions().indexOf( option ) === -1;
}.bind(this));
},this);
Fiddle: http://jsfiddle.net/p3RMD/1/
Edit: Also see the Knockout Projections plugin if you want more efficient .map
and .filter
methods on observableArrays
The standard removeAll method should handle this. From documentation:
myObservableArray.removeAll(['Chad', 132, undefined]) removes all values that equal 'Chad', 123, or undefined and returns them as an array
Do you need to extract the available items without altering the original, all available items array?
If you want to return a new array, without modifying the original array, your best bet is to use a computed observable.
var ViewModel = function(){
this.available = ko.observableArray([1,2,3,4,5]);
this.selected = ko.observableArray([1,3,5]);
this.remaining = ko.computed(function(){
var remaining = ko.observableArray();
remaining(ko.toJS(this.availableOptions))
remaining.removeAll(this.selectedOptions());
return remaining();
}, this);
}
Here's a link to a working example:
http://jsfiddle.net/nathanjones/p3RMD/
Edit: fixed sample code.
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