How to pass object literals as polymer attributes

To test individual insulating elements from the polymer separately, I would like to be able to pass object literals to js for some attributes that usually come from parent elements. It’s hard for me to figure out how to do this. See this sample code. If it worked as I would like, it would display 1 and 2 next to each other, but that didn't work.

<script src="http://www.polymer-project.org/webcomponents.js"></script> <link rel="import" href="http://www.polymer-project.org/components/polymer/polymer.html"> <polymer-element name="my-element" attributes="stuff"> <template> {{stuff.one}} {{stuff.two}} </template> <script> Polymer('my-element', { ready: function () { console.log(this.stuff); } }); </script> </polymer-element> <my-element stuff='{"one": 1, "two": 2}'></my-element> 
+7
javascript polymer web-component
source share
3 answers

A polymer only converts JSON text to an object if you initialize the stuff property with an empty hash:

 Polymer('my-element', { stuff: {}, ready: function () { console.log(this.stuff); } }); 

Without this, the stuff attribute is passed as a string. The same goes for arrays.

+9
source share

Another way to do this:

myElem.html

 <link rel="import" href="http://www.polymer-project.org/1.0/samples/components/polymer/polymer.html"> <dom-module id="my-element"> <template> <div> {{stuff.one}} {{stuff.two}} </div> </template> <script> Polymer({ is: "my-element", properties: { stuff:{ type: Object, value: {"one":"default_1","two":"default_2"} } } }); </script> </dom-module> 

index.html

 <!DOCTYPE html> <html lang="en"> <head> <script src="http://www.polymer-project.org/1.0/samples/components/webcomponentsjs/webcomponents-lite.js"></script> <link rel="import" href="myElem.html"> </head> <body> <my-element></my-element> <my-element stuff={"one":"1","two":"2"}></my-element> </body> </html> 

Result

 default_1 default_2 1 2 
+5
source share
 index.html ... <body unresolved fullbleed layout vertical> <my-post info='{"name":"Alex","id":"123"}' posts='[{"id":"456","name":"post1"},{"id":"789","name":"post2"}]'></my-post> </body> ... my-post.html <link rel="import" href="../../bower_components/polymer/polymer.html"> <polymer-element name="my-post" attributes="info posts" > <template> {{info.name}} <template repeat="{{post in posts}}"> <br> {{post.id}} - {{post.name}} </template> </template> <script> (function () { Polymer({ ready: function() { this.info=JSON.parse(this.info) this.posts=JSON.parse(this.posts) }, }); })(); </script> </polymer-element> 
+3
source share

All Articles