有一段时间,我们需要在上下文中动态添加自定义元素.然后:
>插入的聚合物可以接收一些与另一个结合的属性
属性在上下文中,所以它可以相应地改变.
>在聚合物0.5时,我们可以使用PathObserver将属性绑定到
最近添加的组件的上下文属性.但是,我没有
在聚合物1.0中找到解决方案或等效物.
我创建了一个0.5的例子,对于1.0也是一样.参见下面的聚合物的注射代码.另外,为了清楚起见,您可以看到完整的空白示例.
Ej 0.5:
- <polymer-element name="main-context">
- <template>
- <one-element foo="{{foo}}"></one-element>
- <div id="dynamic">
- </div>
- </template>
- <script>
- Polymer({
- domReady: function() {
- // injecting component into polymer and binding foo via PathObserver
- var el = document.createElement("another-element");
- el.bind("foo",new PathObserver(this,"foo"));
- this.$.dynamic.appendChild(el);
- }
- });
- </script>
- </polymer-element>
请看完整的例子:http://plnkr.co/edit/2Aj3LcGP1t42xo1eq5V6?p=preview
Ej 1.0:
- <dom-module id="main-context">
- <template>
- <one-element foo="{{foo}}"></one-element>
- <div id="dynamic">
- </div>
- </template>
- </dom-module>
- <script>
- Polymer({
- is: "main-context",ready: function() {
- // injecting component into polymer and binding foo via PathObserver
- var el = document.createElement("another-element");
- // FIXME,there's no a path observer: el.bind("foo","foo"));
- this.$.dynamic.appendChild(el);
- }
- });
- </script>
请看完整的例子:http://plnkr.co/edit/K463dqEqduNH10AqSzhp?p=preview
你知道一些解决方法或等价物与聚合物1.0?
解决方法
现在没有直接的方法去做.您应该通过监听父元素的foo属性中的更改并监听以编程方式创建的元素的foo-changed事件来手动执行双重绑定.
- <script>
- Polymer({
- is: "main-context",properties: {
- foo: {
- type: String,observer: 'fooChanged'
- }
- },ready: function() {
- var self = this;
- var el = this.$.el = document.createElement("another-element");
- //set the initial value of child's foo property
- el.foo = this.foo;
- //listen to foo-changed event to sync with parent's foo property
- el.addEventListener("foo-changed",function(ev){
- self.foo = this.foo;
- });
- this.$.dynamic.appendChild(el);
- },//sync changes in parent's foo property with child's foo property
- fooChanged: function(newValue) {
- if (this.$.el) {
- this.$.el.foo = newValue;
- }
- }
- });
- </script>
你可以在这里看到一个工作示例:http://plnkr.co/edit/mZd7BNTvXlqJdJ5xSq0o?p=preview