【问题标题】:Polymer updating array subproperty by model聚合物按模型更新数组子属性
【发布时间】:2016-01-02 02:09:56
【问题描述】:

Polymer 中的数组存在一些问题。我有一个类别数组,其中包含一组项目。这些项目包含几个我想轻松改变的属性。对于此示例,我想切换 item.enabled 属性。这是模板布局:

<template is="dom-repeat" items="{{categories}}" as="category">
    <span>{{category.name}}</span>
    <template is="dom-repeat" items="{{category.items}}" as="item">
        <span>{{item.name}}</span>
        <span>{{item.enabled}}</span>
        <paper-icon-button icon="error" on-tap="toggleEnabled"></paper-icon-button>
    </template>
</template>

我希望toggleEnabled-调用切换属于该类别的特定项目的enabled-属性。

AFAIK,要更新 item.enabled 属性以便更新模板,我需要调用 Polymer 的 set() 方法。需要使用该项目属性的路径(作为字符串)和值来调用此方法:

this.set('categories.x.items.y.enabled', !item.enabled)

在此调用中,x 是类别索引,y 是项目索引。这个问题是我不确定如何(有效地)从toggleEnabled 调用中获取这两个参数。我知道如何获取项目本身:

toggleEnabled: function(e) {
   var item = e.model.item;
}

但除了过度过滤之外,我不确定如何检索索引以更新项目的属性以更新模板。

我忽略了什么?最有效的方法是什么?

【问题讨论】:

    标签: arrays polymer polymer-1.0


    【解决方案1】:

    更新:2016-01-03

    对于上述用例,最简单的方法是直接设置事件model对象。

    点击处理程序:

    toggleEnabled: function (e) {
      e.model.set('item.enabled', !e.model.item.enabled);
    }
    

    如果需要知道您的子属性属于哪个,请将category-index 绑定为图标按钮的属性;否则,替代方案需要 dom 遍历,这会增加不必要的复杂性。

    模板:

    <template is="dom-repeat" items="{{categories}}" as="category" index-as="cat_index">
        <span>{{category.name}}</span>
        <template is="dom-repeat" items="{{category.items}}">
            <span>{{item.name}}</span>
            <span>{{item.enabled}}</span>
            <paper-icon-button cat-index$="{{cat_index}}" icon="error" on-tap="toggleEnabled"></paper-icon-button>
        </template>
    </template>
    

    点击处理程序:

    toggleEnabled: function (e) {
    
      var target = Polymer.dom(e).localTarget; // Normalize the event
      var cat = target.getAttribute('cat-index'); // The parent index
      var item = e.model.index; // Subproperty index
    
      // Do your stuff
      var enabled = this.categories[cat].items[item].enabled;
      this.set(['categories', cat, 'items', item, 'enabled'], !enabled);
      ...
    }
    

    【讨论】:

    • 完全忘记了索引,似乎工作得很好,谢谢!我遇到的唯一问题是e.target.getAttribute()。目标返回了&lt;iron-icon&gt;,但目标的dataHost 属性确实返回了正确的元素,因此该行更改为e.target.dataHost.getAttribute('cat-index'')。谢谢!
    • 经过进一步检查,有时e.target.dataHost.getAttribute('cat-index') 会导致非法调用
    • 我最终没有使用cat_index,只使用模型的set()e.model.set('item.enabled', !e.model.item.enabled)
    • @jdepypere 抱歉,刚刚看到您的消息。我忘了——shadow dom 会自动重新定位事件,所以如果你在paper-icon-button 节点上捕获事件,target 对象自然就是那个。如果您在 shady dom 上运行,则需要对其进行规范化。我将编辑我的答案以使其更清楚。
    • 另外,我真的没有意识到 set 方法被混入了 model 对象! (很确定这不是过去)很高兴你发布了这个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多