【发布时间】:2016-04-28 12:17:20
【问题描述】:
使用 Polymer 制作 SPA,我需要我的自定义组件都使用一个通用的自定义组件,该组件代表我的后端 API,并负责从 API 获取/发布数据。它还用作“缓存”并保存要显示的数据。这样,所有有权访问该单个元素的组件都将共享相同的数据。
所以我想做的是这个......:
<my-api
users="{{users}}"
products="{{products}}">
</my-api>
...但是以编程方式,因为<my-api> 没有在我的所有组件中声明,而是在顶部声明一次,然后通过 JavaScript 传递到层次结构:
Polymer({
is: 'my-component',
properties: {
api: {
observer: '_onApiChanged',
type: HTMLElement
},
products: {
type: Array
},
users: {
type: Array
}
},
_onApiChanged: function(newVal, oldVal) {
if (oldVal)
oldVal.removeEventListener('users-changed', this._onDataChanged);
// Listen for data changes
newVal.addEventListener('users-changed', this._onDataChanged);
// Forward API object to children
this.$.child1.api = newVal;
this.$.child2.api = newVal;
...
},
_onDataChanged: function() {
this.users = this.api.users; // DOESN'T WORK as 'this' === <my-api>
this.products = this.api.products; // Plus I'd have to repeat for every array
}
});
Polymer 是否提供了内置方法来执行此操作?我可以通过编程方式创建 双花括号 绑定吗?
【问题讨论】:
-
为什么需要向下传递 API 元素,而不仅仅是从中传递值?
-
@zacharytamas 因为例如假设
component1只需要监听产品而不是用户,但它的一个子组件subcomponent1需要两者,那么我仍然需要声明一个@component1中的 987654326@ 属性,以便能够将其传递给subcomponent1。这意味着我必须在几乎每个组件中声明所有数据数组,这使得每当我添加新数据类型时维护非常复杂,而且非常冗长。
标签: javascript data-binding polymer