如何将对象文字作为聚合物属性传递 [英] How to pass object literals as polymer attributes
问题描述
为了单独测试我的一些聚合物自定义元素,我希望能够传递js对象文字以获取通常来自父元素的一些属性。我无法弄清楚如何做到这一点。请参阅此示例代码。如果它按照我的意愿工作,它会显示1和2彼此相邻,但它不起作用。
In order to test some polymer custom elements of mine in isolation, I would like to be able to pass in js object literals for some attributes that would ordinarily come from parent elements. I'm having trouble figuring out how to do this. See this example code. If it were working as I would like it to, it would display a 1 and a 2 next to each other, but it doesn'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>
推荐答案
Polymer只将JSON文本转换为对象,如果使用空哈希初始化 stuff
属性:
Polymer only converts the JSON text into an object, if you initialize the stuff
property with an empty hash:
Polymer('my-element', {
stuff: {},
ready: function () {
console.log(this.stuff);
}
});
如果没有这个,会传递 stuff
属性在一个字符串中。数组也是如此。
Without this, the stuff
attribute is passed in as a string. The same goes for arrays.
这篇关于如何将对象文字作为聚合物属性传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!