1

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/

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the fast response Tyrsius.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.