napfernandes
napfernandes

Reputation: 1359

ko.arrayFilter doesn't working

I have this function on Backend:

public JsonResult GetEstados()
{
    List<State> states = new List<State>() {
        new State(1, "Acre", "AC"),
        new State(2, "Alagoas", "AL"),
        new State(3, "Amapá", "AP")
        ...
    };

    List<City> cities = new List<City>() {
        new City(1, "Rio Branco", states[0]),
        new City(2, "Brasília", states[6]), 
        new City(4, "Belo Horizonte", states[12])
        ....
    };

    return Json(new {
        states = states,
        cities = cities
    }, JsonRequestBehavior.AllowGet);
}

The purpose is get a collection of cities and states. When I change the selected state, I want to fill the select element with the cities which belongs to that state. Then, I created the KnockoutJS code below:

function State(state) {

    this.id = state.Id;
    this.name = state.Name;
    this.abbreviation = state.Abbreviation;
}

function Cidade(city) {

    this.id = city.Id;
    this.name = city.Name;
    this.state = new State(ko.toJS(city.State));
}

function IndexViewModel() {

    var self = this;

    self.states = ko.observableArray();
    self.cities = ko.observableArray();
    self.selectedState = ko.observable();
    self.selectedCity = ko.observable();


    self.citiesFromSelectedState = ko.computed(function() {
        return ko.utils.arrayFilter(self.cities(), function(city) {
            return city.state().id() == self.selectedState();
        }
    }, self);

}

var model = new IndexViewModel();
$.ajax({
    type: 'GET',
    async: false,
    url: '/Home/GetEstados/',
    success: function(result) {
        ko.utils.arrayForEach(result.states, function(state) {
            model.states().push(new State(ko.toJS(state)));
        });

        ko.utils.arrayForEach(result.cities, function(city) {
            model.cities().push(new City(ko.toJS(city));
        });
    }
});
ko.applyBindings(model);

Ok, this' the procedure to create an observableArray of cities and states.

In my View, I have the following code to display the states and the cities:

<div class="form-group col-lg-4 col-md-4 col-sm-6 col-xs-12">
    <label class="sr-only" for="estado">State</label>
        <select class="form-control" data-bind="
         options: states, 
         optionsText: 'name', 
         optionsValue: 'id', 
         value: selectedState, 
         optionsCaption: ' '"></select>
</div>

<div class="form-group col-lg-8 col-md-8 col-sm-6 col-xs-12">
    <label class="sr-only" for="cidade">City</label>
        <select class="form-control" data-bind="
         options: citiesFromSelectedState, 
         optionsText: 'name', 
         optionsValue: 'id', 
         value: selectedCity, 
         optionsCaption: ' '"></select>
</div>

But it isn't working properly. Did I do something wrong? Thank you all for the help!

Upvotes: 1

Views: 90

Answers (1)

Damien
Damien

Reputation: 8987

The states observable shouldn't be evaluated, you should add the items to observableArray and to its evaluation. Remove the parenthesis after states :

model.states.push(new State(ko.toJS(state)));

model.states.push adds an item to the observableArray. And model.states().push adds an item to an array which is a copy of the internal state of the observableArray.

Response :

As id isn't an observable, you can't invoke it. You better use this snippet. That will create a dependency between selectedState and citiesFromSelectedState .

self.citiesFromSelectedState = ko.computed(function() {
    var state = self.selectedState();
    return ko.utils.arrayFilter(self.cities(), function(city) {
        return city.state.id == state;
    }
}, self);

Upvotes: 1

Related Questions