[英]Data binding attributes of dynamically created polymer elements
如果我想將兩個聚合物元素的屬性綁定在一起,那么我可以在模板中使用數據綁定並執行以下操作:
<!-- 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-parentelement>
那么如何將對my-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>
有多種方法可以處理這種多態性,但在這種情況下,似乎簡單的模板條件是一個很好的選擇。 IOW,像這樣的東西
<template>
<template if="{{kind == 'vimeo'}}">
Vimeo: {{name}}
</template>
<template if="{{kind == 'soundcloud'}}">
Soundcloud <b>{{name}}</b>
</template>
...
在這里運行版本: http : //codepen.io/sjmiles/pen/FkacJ?edit = 100
這對我來說可以動態添加自定義元素然后綁定它。 我還有一個動態導入元素,然后加載然后綁定它的例子。
這里可運行的代碼: 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.