【问题标题】:Polymer 1.0 Dom-Repeat Bind ArrayPolymer 1.0 Dom-Repeat 绑定阵列
【发布时间】:2015-06-27 20:24:08
【问题描述】:

在尝试更新到 Polymer 1.0 时,我遇到了以下数据绑定问题:

My Polymer 0.5 Webapp 使用重复模板为某些类别生成复选框。所有checked 值都绑定到一个数组 (sortedCatsArray),其中 category-ids 作为键。这是我第一次尝试将该部分更新到 Polymer 1.0,但它不起作用...

    <template is="dom-repeat" items="{{sortedCatsArray}}" as="category">
        <paper-checkbox for category$="{{category.id}}" checked="{{filterChkboxes[category.id]}}"></paper-checkbox>
    </template>

正如您在docs 中所读到的,不再可以使用方括号绑定到 Array-Properties(现在这样:object.property)。有人可以告诉我是否仍然可以将所有生成的复选框值绑定到一个数组中?

更新 #1

正如您在docs 中所读到的,不支持按索引进行数组绑定。因此,我尝试将文档中的该示例用于我的案例并编写了以下代码。如果我运行此代码,它似乎按预期工作:选中了第一个和第三个复选框。但如果我手动选中/取消选中复选框,我也希望更改数组。这不会发生,只有当我更改数组(在ready-函数中)复选框才会被选中...

<dom-module id="my-index">
<link rel="import" type="css" href="/css/index.css">
    <template>  
        <template is="dom-repeat" items="{{sortedCatsArray}}" as="category">
            <paper-checkbox for category$="{{category.id}}" checked="{{arrayItem(filterChkboxes.*,category.id)}}" on-change="test"></paper-checkbox>
        </template>
    </template>
</dom-module>
<script>
  Polymer({
    is: "my-index",
    properties: {
        filterChkboxes: {
            type: Array,
            notify: true,
            observer: "filterChkboxesChanged",
            value: function(){return[true,false,true,false];}
        },
        sortedCatsArray: {
            type: Array,
            value: function(){return[{id: 0}, {id: 1},{id: 2},{id: 3}]},
            notify: true        
        },      
    },
    ready: function(){
        this.set('filterChkboxes.1',true);
    },
    test: function(){
        console.log(this.filterChkboxes);
    },
    observers: [
        'filterChkboxesChanged(filterChkboxes.*)'
    ],
    arrayItem: function(array, key){
        return this.get(key, array.base);
    },
    filterChkboxesChanged: function(changes){
        console.log(changes);
    },
  });
</script>

【问题讨论】:

    标签: javascript html polymer-1.0


    【解决方案1】:

    正如docs 中所述,您不能在绑定注释中使用表达式。而不是 checked="{{filterChkboxes[category.id]}}" 定义一个 computed property 并将其替换为类似 checked="{{get_filterChkboxes(category.id)}}" 的东西,其中 get_filterChkboxes 是一个计算属性,您应该相应地定义。

    【讨论】:

    • 您有这种方式的工作示例吗?我想,checked-attribute 绑定到大括号中的属性。所以计算的属性应该返回一个变量,其中存储了checked-state。不是吗?但这在我的尝试中不起作用......
    • 是的,没错。发布您正在尝试但无法正常工作的简单但完整的版本,以便有人更容易发现问题。另外,请仔细查看herehere
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多