Asle G
Asle G

Reputation: 588

How to make checkboxes work with knockout

I found this example from Ryan Niemeyer and started to manipulate it into the way I write my own code, but then it stopped working. Can anybody tell me why?

Alternative 1 is my variant Alternative 2 is based upon Ryans solution and does work (just comment/uncomment the Applybindings).

Why doesn´t Alternative 1 work?

My issue is with the filteredRows:

self.filteredRows = ko.dependentObservable(function() {
    //build a quick index from the flags array to avoid looping for each item
    var statusIndex = {};

    ko.utils.arrayForEach(this.flags(), function(flag) {
      statusIndex[flag] = true;
    }); 

    //return a filtered list
    var result = ko.utils.arrayFilter(this.Textbatches(), function(text) {
        //check for a matching genré
        return ko.utils.arrayFirst(text.genre(), function(genre) {
            return statusIndex[genre];
        });
        return false;
    });

    console.log("result", result);
    return result;

});

I want to filter my Textbatches on the genre-attribute (string in db and the data collected from the db is a string and not an array/object)

Fiddle here: http://jsfiddle.net/gsey786h/6/

Upvotes: 0

Views: 86

Answers (1)

nemesv
nemesv

Reputation: 139808

You have various problems, most of them can be simply fixed with checking your browser's JavaScript console and reading the exceptions...

So here is the list what you need to fix:

  • You have miss-typed Textbatches in the declaration so the correct is self.Textbatches = ko.observableArray();

  • You have scoping problem in filteredRows with the this. So if you are using self you should stick to it and use that:

    • this.flags() should be self.flags()
    • this.Textbatches() should be self.Textbatches()
  • Your genre property has to be an array if you want to use it in ko.utils.arrayFirst

  • Finally your Textbatch takes individual parameters but you are calling it with an object, so you need to change it to look like:

    Textbatch = function(data) {
        var self = this;
        self.id = ko.observable(data.id);
        self.name = ko.observable(data.name);
        self.statuses = ko.observableArray(data.status);
        self.genre = ko.observableArray(data.genre);
        self.createdBy = ko.observable(data.createdBy);  
    };
    

    or you can of course change the calling places to use individual arguments instead of an object.

Here is a working JSFiddle containing all the above mentioned fixes.

Upvotes: 2

Related Questions