Naz*_*rke 6 javascript polymer
需要在另一个聚合物元素的脚本中动态创建聚合物元素offices-list,如下所示:
<dom-module id="contacts-tag">
<template>
<iron-ajax ... on-response = "handleResponse"></iron-ajax>
</template>
<script>
Polymer({
is: "contacts-tag",
handleResponse: function(request){
var response = request.detail.response;
this.officesRegions = response.officesRegions;
this.officesCities = response.officesCities;
var dynamicEl = document.createElement("offices-list");
dynamicEl.setAttribute("regions", this.officesRegions);
dynamicEl.setAttribute("cities", this.officesCities);
document.body.appendChild(dynamicEl);
}
});
</script></dom-module>
Run Code Online (Sandbox Code Playgroud)
但是,只要它到达"document.createElement("offices-list");" 这个新标签内的元素开始渲染,并且已经调用了ready方法,而我在设置属性后期望它们发生.我该怎么做?
编辑:似乎问题具有不同的性质.我将对象设置为属性,"offices-list"标签无法识别它们,因此无法访问它或循环访问它.然后,我的问题将改为"如何绑定对象?"
zer*_*evx 11
我认为正确的答案是 - 这取决于你想要实现的目标.
如果你正在寻找命令式数据绑定,即你想动态地将这样的东西添加到模板中,
<offices-list offices-regions="{{regions}}"
offices-cities="{{cities}}">
</offices-list>
Run Code Online (Sandbox Code Playgroud)
你运气不好,因为Polymer 1.0不支持命令式数据绑定.
如果你只是想在参数(传递NOT数据绑定)到一个动态创建的元素,无论是el.setAttribute()和el.myAttribute = this.myAttribute应该工作.
由于您使用的是Polymer,我认为您应该尝试在框架内(在Polymer模板实例中)包含DOM操作,而不是直接添加到document.body类似的东西.
<dom-module id="contacts-tag">
<template>
<iron-ajax ... on-response="handleResponse"></iron-ajax>
<div id="insertion_point"></div>
</template>
<script>
Polymer({
is: "contacts-tag",
handleResponse: function(request) {
...
Polymer.dom(this.$.insertion_point).appendChild(dynamicEl);
}
});
</script>
</dom-module>
Run Code Online (Sandbox Code Playgroud)
最后,如果您的目的是<contacts-tag>在ajax请求完成后简单地显示一个,我认为您可以以声明方式实现此目的.
<dom-module id="contacts-tag">
<template>
<iron-ajax ... on-response="handleResponse"></iron-ajax>
<template is="dom-if" if="{{_unveilOfficesListWhenReady}}">
<offices-list offices-regions="{{_regions}}"
offices-cities="{{_cities}}">
</offices-list>
</template>
</template>
<script>
Polymer({
is: "contacts-tag",
properties: {
_regions: String,
_cities: String,
_unveilOfficesListWhenReady: { type: Boolean, value: false }
},
handleResponse: function(request) {
var response = request.detail.response;
this._regions = response.officesRegions;
this._cities = response.officesCities;
this._unveilOfficesListWhenReady = true;
}
});
</script>
</dom-module>
Run Code Online (Sandbox Code Playgroud)
不需要动态元素.
您不应该使用,setAttribute但应直接设置相应的属性.
var dynamicEl = document.createElement("offices-list");
dynamicEl.regions = this.officesRegions;
dynamicEl.cities = this.officesCities;
document.body.appendChild(dynamicEl);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15712 次 |
| 最近记录: |