1

Whenever I save my item I remap the model doing the following:

ko.mapping.fromJS(data, {}, deal);

My model looks like:

{
  "DealId": 0,
  "BrokenRules": [
    {
      "Property": "EndDate",
      "Description": "End Date is required."
    },
    {
      "Property": "CustomerId",
      "Description": "Customer is required."
    },
    {
      "Property": "LiveState",
      "Description": "Live State is required."
    },
    {
      "Property": "WorkState",
      "Description": "Work State is required."
    }
}

I want to set the css class on a div based on the contents of the BrokenRules array and was hoping I could do something like:

    <div class="control-group" data-bind="css: { error: BrokenRules.filterByProperty('Property', 'EndDate').length !== 0 }">
        <label class="control-label">End Date</label>
        <div class="controls">
            <input type="text" class="span2" name="EndDate" data-bind="value: EndDate, enable: $index() === 0" />
        </div>
    </div>

But this doesn't seem to work. My filterByProperty, while firing the first time, doesn't have any items, and for some reason, never fires again.

ko.observableArray.fn.filterByProperty = function (propName, matchValue) {
    return ko.computed(function () {
        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;
    }, this);
}

The filterByProperty was taken right from the knockoutjs site.

Any help on doing this would be much appreciated! Thanks!

1 Answer 1

2

The filterByProperty function is returning a ko.computed. In order to get the actual array, you need to execute the computed to get the underlying JavaScript array, and then you can check the length.

Notice the extra parentheses after filterByProperty()

<div class="control-group" data-bind="css: { error: BrokenRules.filterByProperty('Property', 'EndDate')().length !== 0 }">

See the Fiddle

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

2 Comments

That worked perfectly! I swear those extra parentheses are going to be the death of me! :)
If you set up your computed to return an observableArray, then you could have two sets of them :)

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.