【发布时间】:2015-06-12 18:05:53
【问题描述】:
如何在自动绑定模板(即声明为 <template is='dom-bind'>...</template> 的模板)中定义计算绑定?
【问题讨论】:
标签: polymer polymer-1.0
如何在自动绑定模板(即声明为 <template is='dom-bind'>...</template> 的模板)中定义计算绑定?
【问题讨论】:
标签: polymer polymer-1.0
只需通过脚本将计算绑定直接分配给模板元素,确保在计算绑定定义之后初始化所涉及的属性。
例子:
<template is="dom-bind">
<div>
<input value="{{text::input}}">
</div>
<div>[[describe(text)]]</div>
</template>
<script>
(function() {
var template = document.querySelector('template[is="dom-bind"]');
template.describe = function(text) {
if (text) {
return 'You entered "' + text + '", which is ' + text.length + ' characters long.';
} else {
return 'You didn\'t even enter a thing! Shame on you.';
}
};
template.text = '';
})();
</script>
【讨论】:
var template = document.querySelector('...'); 之后立即初始化 template.text = 'initial text';,则计算的绑定不会立即呈现:我在控制台输出 [dom-bind::_annotatedComputationEffect]: compute method 'describe' not defined 中收到警告。但是,当我开始在输入框中输入时,绑定确实发生了。对此有什么想法吗?
setTimeout 延迟来模拟我正在处理的环境。这里的要点是,从声明is="dom-bind" 元素到执行定义describe 的代码可能需要一些时间。在常规聚合物元件中,这不是问题,因为所有必要的结合都会及时发生。 (我还添加了template.text = 'initial text'; 以明确计算的绑定最初不是计算的。查找[dom-bind::_ ... method 'describe' not defined 警告。)
<template> 定义之后立即设置的,那么应该不会有任何问题,因为它会在加载文档之前执行,也就是 Polymer 标记模板的时候。