我想创建聚合物自定义元素,模拟游戏中角色的背包。我想要实现的结构示例:
<eq-backpack>
<eq-slot></eq-slot>
<eq-slot><eq-item></eq-item></eq-slot>
<eq-slot></eq-slot>
<eq-slot><eq-item></eq-item></eq-slot>
</eq-backpack>
在<eq-backpack>
中,我迭代背包中的元素:
<template repeat="{{item in backpack}}">
<eq-slot></eq-slot>
</template>
在<eq-slot>
中,我检查插槽是否为空:
<template if="{{item != null}}">
<eq-icon></eq-icon>
</template>
现在我想将非原始数据(对象包含项属性 - 传递给许多人作为属性传递给<eq-slot>
,然后在元素创建期间传递给<eq-item>
或紧随其后。我怎么能这样做?
我知道两种肮脏的方式:定义一些原始属性,如:
<eq-slot itemId="item.itemId"></eq-slot>
然后尝试从某些全局数据结构中获取项目,但我想避免维护全局变量。
我也可以通过<eq-slot>
手动创建var el = new Element.tag("eq-item")
,然后调用一些setter el.item = item
,但它不像声明方式那么优雅。
还有其他可能吗?
答案 0 :(得分:3)
您可以直接在聚合物代码中使用它:
在eq-backpack
:
<eq-backpack>
<template repeat="{{item in backpack}}">
<eq-slot item="{{item}}"></eq-slot>
</template>
</eq-backpack>
需要在您的eq-slot元素上使用@published ItemType item
。
在eq-slot
<template if="{{item}}">
<eq-icon name="{{item.iconName}}"></eq-icon>
</template>
您可以直接将数据绑定到eq-slot。这是你想要的吗?
您不需要任何全局数据。
我写了一篇关于聚合物元素中数据绑定的博客文章。也许这有助于你:
http://www.roberthartung.de/nested-polymer-elements-and-data-binding-in-googles-dart/
问候,罗伯特