根据可观察数​​组中的项设置knockout css绑定

时间:2013-05-02 13:55:55

标签: knockout.js knockout-mapping-plugin

每当我保存我的项目时,我都会重新映射模型,执行以下操作:

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

我的模型看起来像:

{
  "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."
    }
}

我想根据div数组的内容在BrokenRules上设置css类,并希望我可以这样做:

    <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>

但这似乎不起作用。我的filterByProperty在第一次触发时没有任何物品,并且由于某种原因,再也不会发射。

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);
}

filterByProperty是从knockoutjs网站直接拍摄的。

任何有关这方面的帮助将非常感谢!谢谢!

1 个答案:

答案 0 :(得分:2)

filterByProperty函数返回ko.computed。为了获得实际的数组,你需要执行computed来获取底层的JavaScript数组,然后你可以检查它的长度。

注意filterByProperty()

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

See the Fiddle