2015-02-07 45 views
0

使用重複和在表達它是微不足道的迭代數組,但交換替代「在」表達用於遍歷對象聚合物(0.5.4)

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

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

無法遍歷該對象。我已經看到使用Object.key爲了獲得每個值的例子,但返回的索引是0,1而不是「foo」「bar」。

儘管這個簡單的例子並沒有使用2路綁定,但我仍想繼續支持它,以防將來需要它。

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

回答

3

雖然有[但]沒有內置遍歷對象的能力,你可能很容易與過濾實現這一功能問題,請不要猶豫,問。

Live:http://jsbin.com/munehitogu/1/edit

+0

數據變化時會發生什麼? – 2015-02-07 18:19:40

+0

'repeat'重新執行。我添加了一個實時預覽鏈接。 – mudasobwa 2015-02-07 18:21:09

+0

http://jsbin.com/ficimeqari/1/我已經添加了一個我認爲應該重複更改數據的任務。 – 2015-02-07 18:30:06