替代 "in" 表达式迭代对象聚合物 (0.5.4)

Alternative to "in" expression for iterating over objects polymer (0.5.4)

使用 repeat 和 in 表达式迭代数组很简单,但是交换

            this.data = ["foo","bar"];

            this.data = {foo:"football",bar:"barfly"}

无法迭代对象。我见过使用 Object.key 来获取每个值的示例,但返回的索引是 0,1 而不是 "foo" "bar".

虽然这个简单的例子没有使用双向绑定,但我想继续支持它,以备日后需要。

http://jsbin.com/copogeyome/1/

<!DOCTYPE html>
<html>
  <head>
    <meta charset=utf-8 />
    <title>Polymer</title>
    <script src="http://www.polymer-project.org/components/webcomponentsjs/webcomponents.js"></script>
    <link rel="import" href="http://www.polymer-project.org/components/polymer/polymer.html">
</head>
<body>
<polymer-element name="an-consumer" attributes="data" noscript>
    <template>testing {{data.foo}}<br>
        <template id="foo">f {{}}<br></template>
        <template id="bar">b {{}}<br></template>
        <template id="0">0 {{}}<br></template>
        <template id="1">1 {{}}<br></template>
        <template id="2">2 {{}}<br></template>
        {
        <template repeat="{{obj,index in data}}" bind="{{data}}">
            ( {{index}} - {{obj}} ) = <template ref="{{index}}" bind="{{obj}}"></template>
        </template>
        }
    </template>
</polymer-element>
<polymer-element name="an-supplier" attributes="data">
    <template></template>
    <script>
    Polymer({
        ready: function(){
            this.data = ["foo","bar"];
            //this.data = {foo:"football",bar:"barfly"}
        }
    });
    </script>
</polymer-element>
<polymer-element name = "an-root" noscript>
    <template>
        <an-supplier data="{{stuff}}"></an-supplier>
        <an-consumer data="{{stuff}}"></an-consumer>
    </template>
</polymer-element>
<an-root>
</an-root>
</body>
</html>

虽然 [还] 没有内置的对象迭代能力,但您可以使用 filter 轻松实现此功能:

<template repeat="{{key in data | getKeys}}">
  <span>Key: {{key}}</span>
  <span>Value: {{data[key]}}</span>
</template>

<script>
Polymer({
  ready: function(){
    // this.data = ["foo","bar"];
    this.data = {foo:"football",bar:"barfly"}
  }
  // filter function to use in looping objects
  getKeys : function(o) {
    return Object.keys(o);
  }
});
</script>

如果您还有其他问题,请随时提出。

直播:http://jsbin.com/munehitogu/1/edit