如果我想将两个聚合物元素的属性绑定在一起,那么我可以在模板中使用数据绑定并执行以下操作:
<!-- 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-childelement>
内使用document.createElement()
动态创建一个元素(让我们称之为)<my-parentelement>
,那么如何同步对我的属性所做的更改-childelement with my-parent element?
一个选项是从子元素发出事件并在父元素中订阅它们,但是当我有很多我希望保持同步的属性然后我必须管理添加/删除侦听器时,这很乏味每当childelement被替换为不同的子元素时。
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>
答案 0 :(得分:4)
有多种方法可以处理这种多态性,但在这种情况下,似乎简单的模板条件是一个很好的选择。 IOW,像这样
<template>
<template if="{{kind == 'vimeo'}}">
Vimeo: {{name}}
</template>
<template if="{{kind == 'soundcloud'}}">
Soundcloud <b>{{name}}</b>
</template>
...
答案 1 :(得分:3)
这适用于我动态添加自定义元素然后绑定它。我还有一个动态导入元素,然后加载然后绑定它的例子。
此处可运行代码:https://github.com/semateos/polymer-lazy-load
演示app.html:
<link rel="import" href="/bower_components/polymer/polymer.html">
<link rel="import" href="lazy-test.html">
<polymer-element name="demo-app" attributes="session">
<template>
<input type="text" value="{{session.id}}">
<button on-tap="{{buttonClick}}">Test</button>
<div id="holder"></div>
</template>
<script>
Polymer({
buttonClick: function(e){
//create the polymer element
var child = document.createElement('lazy-test');
//bind the session value to the parent
child.bind('session', new PathObserver(this, 'session'));
//attach it to the parent
this.$.holder.appendChild(child);
},
created: function() {
//set the initial value
this.session = {id: '123'};
}
});
</script>
</polymer-element>
懒惰的test.html:
<link rel="import" href="/bower_components/polymer/polymer.html">
<polymer-element name="lazy-test" attributes="session">
<template>
<h1>Lazy Child: {{session.id}}</h1>
<input type="text" value="{{session.id}}">
</template>
<script>
Polymer({
created: function() {
// hint that session is an object
this.session = {};
}
});
</script>
</polymer-element>