考虑以下自定义 polymer 元素的用法
<app-header bar-foo="[[abc.def.ghi]]" app-title="[[appTitle]]"></app-header>
这里我将两个变量绑定(bind)到自定义元素 app-header
。现在,当我想更新值时,您可能希望按如下方式执行此操作(在 app-header
的父级中!):
this.abc.def.ghi = 10;
this.appTitle = 'New title';
但是,这只会更新 appTitle
而不是 abc.def.ghi
。为了也更新此值,您需要执行以下操作:
this.abc = {def: {ghi: 10}};
如果有人知道这是为什么,请告诉我!!
无论如何,正因为如此,我想使用Immutable
!
然而,这引入了一些关于数据如何绑定(bind)到自定义元素的问题
这是一个示例片段:
<dom-module id="my-app">
<template>
<app-header hits="[[state.get('page').get('hits')]]"></app-header>
</template>
<script>
(function () {
class MyApp {
beforeRegister() {
this.is = 'my-app';
this.properties = {
state: {
type: Object,
notify: true,
value: Immutable.Map({
page: Immutable.Map({hits: 10})
})
}
};
}
}
Polymer(MyApp);
})();
</script>
</dom-module>
所以问题出现在给元素绑定(bind)数据的时候:
<app-header hits="[[state.get('page').get('hits')]]"></app-header>
这样的事情有可能吗,还是我做的其他事情完全错了?
最佳答案
更新结构数据时,您应该使用 Polymer API。这将触发更改的事件,绑定(bind)的数据将更新。看看this article在路径更改通知上。在这种情况下,您需要将代码更改为:
this.set('abc.def.ghi', 10);
我不熟悉 Immutable,但是,Polymer 不支持这种表达式。
hits="[[state.get('page').get('hits')]]"
您可以绑定(bind)到元素的(子)属性或计算函数。计算函数必须在您的元素中定义。您不能在数据绑定(bind)中对任意对象调用任意函数。
也许,使用 set
API 将消除使用 Immutable 的需要。
关于javascript - polymer 数据绑定(bind)和 Immutable.js 结合在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33236740/