Pat Hastings
Pat Hastings

Reputation: 412

Knockout adding computed breaks observable array

Hi I am trying to use a computed value to make a filtered version of an observable array as per the example here http://knockoutjs.com/documentation/fn.html ( right at the bottom).

For the html I have have

<select  width="50px" data-bind="options: $root.resources, optionsText: 'Name'"></select>
<select  width="50px" data-bind="options: $root.available, optionsText: 'Name'"></select>​

And my viewModel looks like this:

var viewModel = function() {
    var self = this;
    self.resources = ko.observableArray([{Name: "Anna",Available: true}, {Name: "Bert", Available: false}]);  

    self.getFilteredResources = function (isAvailable) {
        var all = self.resources(), results = [];
        var resource;
        for (resource in all){
            if (resource.Available() === isAvailable){
                results.push(resource);
            }
        }
        return results;
    };    
    //self.available = ko.computed(function() { self.getFilteredResources( true);}, this);    
};

ko.applyBindings(new viewModel());​

You can also see the code here http://jsfiddle.net/patrickhastings/eCtFY/1/

As it stands the out put is one dropdown with Anna and Bert in it and one empty which is fine.

When I uncomment out the line to declare self.available instead of the second dropdown being populated with Anna, I get two empty drop downs. Help Please tell me where I am being dumb.

Upvotes: 1

Views: 518

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

A couple small issues in this one:

You are calling resource.Available() and Available is not an observable, so you just need to check resource.Available === isAvailable.

Additionally, your computed observable needs to return the result of self.getFilteredResources

Doing for resource in all will give you the index rather than the resource itself.

I would recommend something like: http://jsfiddle.net/rniemeyer/jCYT7/

Upvotes: 1

Related Questions