我有这两个自定义聚合物元素(聚合物 1.0.3):
- 显示要翻译的文本。
- 显示按钮以触发加载翻译。
我也有一个行为保存翻译(json 对象)并包含使翻译成为可能的所有功能。
这是我期望发生的事情:
- 单击元素 2 中的按钮
- 翻译加载到行为中
- 语言选择在行为中设置
- 元素 1 中的文本使用翻译后的等价物进行更新
步骤 1 - 3 发生,但 4 没有。文本永远不会更新。如果元素 1 和 2 组合为同一个元素,我可以让它工作,但如果它们是分开的(任何它们需要分开),我就不能让它工作。
如果您想知道“踢”属性,这是我从 Polymer 0.5 中学到的。当这两个元素结合起来时,它就可以工作了,所以我认为当元素分开时它是必要的。
知道我怎样才能做到这一点吗?我对替代范式持开放态度。
代码
这大致是我的代码的布局方式。我还用单页测试用例做了一个 plunker。
索引.html
<!doctype html>
<html>
<head>
<script src="http://www.polymer-project.org/1.0/samples/components/webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="http://www.polymer-project.org/1.0/samples/components/polymer/polymer.html">
<link rel="import" href="behavior.html">
<link rel="import" href="element1.html">
<link rel="import" href="element2.html">
</head>
<body>
<my-element></my-element>
<another-element></another-element>
</body>
</html>
元素 1
<dom-module id="my-element">
<template>
<p>{{localize(label, kick)}}</p>
</template>
</dom-module>
<script>
Polymer({
is: 'my-element',
behaviors: [
behavior
],
properties: {
label: {
type: String,
value: 'original'
}
}
});
</script>
元素 2
<dom-module id="another-element">
<template>
<button on-click="buttonClicked">load</button>
</template>
</dom-module>
<script>
Polymer({
is: 'another-element',
behaviors: [
behavior
],
buttonClicked: function() {
this.registerTranslation('en', {
original: 'changed'
})
this.selectLanguage('en');
}
});
</script>
行为
<script>
var behavior = {
properties: {
kick: {
type: Number,
value: 0
},
language: {
type: String,
value: 'fun'
},
translations: {
type: Object,
value: function() {
return {};
}
}
},
localize: function(key, i) {
if (this.translations[this.language] && this.translations[this.language][key]) {
return this.translations[this.language][key];
}
return key;
},
registerTranslation: function(translationKey, translationSet) {
this.translations[translationKey] = translationSet;
},
selectLanguage: function(newLanguage) {
this.language = newLanguage;
this.set('kick', this.kick + 1);
}
};
</script>