Rolando
Rolando

Reputation: 762

filtering data from the server (using knockout)

I am working in a page using html/js/knockout. this page contains a table wich is populated from the a service. Also this page contains filters like select controls where the user is able to select item on this controls and see a new updated table with data. Connection with the server and drawing the table are workig fine. The issue what I have is how to handle the load of my table using the filters because the first I am calling my service with all the default parameters. my code is something like:

export var selectedType= ko.observable();

export function activate() {    
  loadInitData();
}

function loadInitData() {
   datacontext.getTypes(TypesObservable);
  datacontext.getRegistration(registrationsObservable, 'allTypes'); //just making simple
}

selectedType.subscribe(function (newValue) {    
   //calling to my service.
    datacontext.getRegistration(registrationsObservable, newValue.name);
   //My issue: this section is called also when my registrationsObservable are populated the first time.
 });

The issue with this code is that the table is populated more than one time. (actualy i have 3 more filters in my page). this link show somthing similar what I have described: http://jsfiddle.net/rolandomartinezg/U66n9/2/

Thank you!

Upvotes: 0

Views: 76

Answers (2)

techsaint
techsaint

Reputation: 772

You can use a computed field like this:

vm.registrationsFiltered = ko.computed(function() {
         //return
    if(vm.selectedFruit && vm.selectedFruit() && vm.selectedFruit().name){
     return  $.grep(vm.registrations(),
                           function(item,idx){
                               return item.name === vm.selectedFruit().name
                           });


    }
    }, this);

and then change your view to use the new filtered property instead. I've added it to your fiddle here: http://jsfiddle.net/U66n9/9/

Upvotes: 1

lagerone
lagerone

Reputation: 1767

If you add an optionsCaption then selectedFruit will remain empty until a selection is made.

http://jsfiddle.net/danne567/U66n9/5/

<select data-bind="options: items, optionsText: 'name', optionsCaption: 'Select fruit', value: selectedFruit"></select>

<span data-bind="text: selectedFruit() ? selectedFruit().name : ''"></span>

Upvotes: 1

Related Questions