【发布时间】:2014-06-04 23:21:03
【问题描述】:
如果我想将两个聚合物元素的属性绑定在一起,那么我可以在模板中使用数据绑定并执行以下操作:
<!-- Publish .items so others can use it for attribute binding. -->
<polymer-element name="td-model" attributes="items">
<script>
Polymer('td-model', {
ready: function() {
this.items = [1, 2, 3];
}
});
</script>
</polymer-element>
<polymer-element name="my-app">
<template>
<td-model items="{{list}}"></td-model>
<polymer-localstorage name="myapplist" value="{{list}}"></polymer-localstorage>
</template>
<script>
Polymer('my-app', {
ready: function() {
// Initialize the instance's "list" property to empty array.
this.list = this.list || [];
}
});
</script>
</polymer-element>
来自http://www.polymer-project.org/articles/communication.html#binding
但是,如果我在另一个元素 <my-parentelement> 中动态使用 document.createElement() 创建一个元素(我们称之为)<my-childelement>,那么我如何同步对 my-childelement 的属性所做的更改与 my-parent元素?
一种选择是从子元素发出事件并在父元素中订阅它们,但是当我有很多要保持同步的属性并且必须管理添加/删除侦听器时,这很乏味每当子元素被不同的子元素替换时。
Node.bind() 看起来可能是之后,但我不确定我是否误解了它的目的。
我希望能够按照以下方式做一些事情:
<polymer-element name="my-parentelement" attributes="shape">
<script>
Polymer('my-parentelement', {
shape: square,
ready: function() {
var child = document.createElement('my-childelement');
this.bind('shape', new PathObserver(child, 'shape');
// Now this.shape will be kept in sync with child.shape, e.g.
child.shape = 'triangle';
this.shape == child.shape; // evaluates to true
}
});
</script>
</polymer-element>
【问题讨论】:
-
我意识到人们不直接回答您的问题时通常很烦人,但是使用
<template>管理元素要容易得多,特别是所有花哨的数据绑定机制都是声明性的。 IOW,我宁愿帮助您避免createElement,也不愿提供咒语来执行命令式绑定。你愿意更全面地描述你的核心问题吗? -
没问题!我正在创建一堆元素,这些元素提供统一的 API 来嵌入各种媒体网站的播放器,例如 YouTube、SoundCloud 和 Vimeo。然后我创建一个通用的
player元素,它有一个source属性,可以设置为一个URL(http://www.youtu.be/v/VMVj_jR75vE或https://soundcloud.com/thump/mesck-conquista等),它将在内部使用正确的子元素并绑定子元素 API 到它自己的 API。让我知道带有伪代码的要点是否会使事情更清楚!
标签: javascript polymer