【问题标题】:Set knockout css binding based on item in observable array根据可观察数​​组中的项目设置淘汰赛 css 绑定
【发布时间】:2013-04-26 17:41:57
【问题描述】:

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

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

我想根据 BrokenRules 数组的内容在 div 上设置 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 网站。

对此的任何帮助将不胜感激!谢谢!

【问题讨论】:

    标签: knockout.js knockout-mapping-plugin


    【解决方案1】:

    filterByProperty 函数返回一个ko.computed。为了得到实际的数组,你需要执行计算得到底层的JavaScript数组,然后你可以检查长度。

    注意filterByProperty()之后的额外括号

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

    See the Fiddle

    【讨论】:

    • 效果很好!我发誓那些额外的括号将是我的死亡! :)
    • 如果你设置你的计算返回一个 observableArray,那么你可以有两组:)
    猜你喜欢
    • 2014-09-28
    • 2015-10-05
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 2020-11-20
    • 1970-01-01
    相关资源
    最近更新 更多