在我的理想世界中,我希望聚合物组件能够透明地使用Object.observe()来侦听模型属性的变化,而模型对象本身不必是自定义元素。
在下面的示例中,我有一个元素,其属性model类型为Object。HTML使用{{model.name}},每当该属性发生更改时,我希望元素自动更新。
在我的演示/示例中,我实现这一目标的方法是在自定义代码中使用Object.observe(),当发生任何更改时,我将model设置为undefined并再次返回。这个“刷新”UI并获取更改。当然,在任何非平凡的UI中,这都是很简陋的,所以这是一个“希望不是策略”的时刻.
现在是否有任何设计模式来简洁地做这类事情,和/或将来做这类事情的路线图?
这是我的自定义元素:
<link rel="import" href="../bower_components/polymer/polymer.html">
<dom-module id="test-view">
<template>
<p>Hello, I am called <span>{{model.name}}</span>, how are you?</p>
</template>
</dom-module>
<script>
Polymer({
is: 'test-view',
properties: {
model: Object,
},
observers: [
'_modelChanged(model)'
],
ready: function() { },
attached: function() { },
detached: function() { },
_modelChanged: function(model) {
if (model) { Object.observe(model, this._observer.bind(this)); }
},
_observer: function() {
const oldModel = this.model;
this.model = undefined;
this.model = oldModel;
}
});
</script>这是一个HTML页面,驱动它完成状态转换:
<html>
<head>
<script src="../bower_components/webcomponentsjs/webcomponents.js"></script>
<link rel="import" href="../test-view/test-view.html">
</head>
<body>
<test-view id="first" model='{ "name": "Wilma" }'></test-view>
<script>
const newModel = { name: 'Fred' };
const testView = document.querySelector('#first');
window.setTimeout(function() { testView.model = newModel; }, 2000);
window.setTimeout(function() { newModel.name = 'Barney'; }, 4000);
</script>
</body>
</html>发布于 2015-08-05 06:48:31
这可能不是你的问题的完整答案,更多的评论,但由于代码看起来不太好的注释,我仍然张贴它作为一个答案。我认为,如果没有额外的观察员,这种事情甚至可能在0.5中起作用。但是,为了提高性能,这种行为在1.0中被删除了。我也希望我们什么时候能把它拿回来。
为了避免将模型设置为“未定义”和“返回”以触发刷新,您还可以将更改通知聚合物。我假设这会更有效,特别是当您有复杂的对象和大量的数据绑定时。
_observer: function(changes) {
changes.forEach(function(change){
this.notifyPath("model." +change.name, change.object[change.name]);
}.bind(this));
}https://stackoverflow.com/questions/31819504
复制相似问题