MadDogMcFie
MadDogMcFie

Reputation: 139

Knockoutjs observableArray not binding

I'm trying to take my init array and filter it by using a custom function like (http://knockoutjs.com/documentation/fn.html), but rather than creating a new array I'm just overwriting the old one. I'm clicking on the PO . In memory it is working but it's not binding to the DOM once it's done. Is this because I'm rewriting the array rather than removing items from the existing array?

http://jsfiddle.net/chadrickm/39xsC/

Upvotes: 1

Views: 484

Answers (2)

Facio Ratio
Facio Ratio

Reputation: 3393

I don't know whether it's the only problem, but to set the value of an observableArray, do this:

self.materialTrans(x);

Instead of this:

self.materialTrans = x;

Where x is the new filtered array, of course.

Upvotes: 0

Kyeotic
Kyeotic

Reputation: 19857

This won't work because the binding is going to break on this line:

self.materialTrans = self.materialTrans.filterByProperty("PO", item.PO);

Knockout observables cannot be overwritten. If you want to update their value, you need to pass the new value in as an argument. The binding is to the old function, which you are removing by reassigning it. One way to make this work be like to do this:

self.materialTrans(self.materialTrans.filterByProperty("PO", item.PO));

and change your function to just return an array:

ko.observableArray.fn.filterByProperty = function(propName, matchValue) {

        var allItems = this(),
            matchingItems = [];
        for (var i = 0; i < allItems.length; i++) {
            var current = allItems[i];
            if (ko.utils.unwrapObservable(current[propName]) === matchValue) matchingItems.push(current);
        }
        return matchingItems;
};

Here is the updated fiddle. If I misunderstood your goal, just let me know.

Upvotes: 2

Related Questions