我有<dom-module>
一个 Array 类型的属性locations
,每隔一段时间就会在外部更新:
<dom-module id="my-map">
<template>
<google-map api-key="MY_API_KEY" id="map" libraries="visualization,geometry,drawing">
<template is="dom-repeat" items="{{locations}}" as="user">
<template is="dom-repeat" items="{{user.trace}}">
<google-map-marker latitude="{{item.latitude}}" longitude="{{item.longitude}}">
</google-map-marker>
</template>
</template>
</google-map>
</template>
</dom-module>
<script>
Polymer({
is : 'my-map',
properties : {
locations : {
type : Array,
value : [],
observer : '_locationsChanged'
}
},
ready : function(){
var self = this;
this.map = this.querySelector('google-map');
this.map.addEventListener('google-map-ready',function(){
// some styling happening here.
});
},
_locationsChanged : function(newLocations, oldLocations){
// this fires correctly! ...
}
});
</script>
在另一个模块中,我发送一个 AJAX 请求来检索要在地图上显示为标记的数据。请求完成后,我会更新位置属性,并且_locationsChanged
回调会很好地触发。
这种情况下的数据如下所示:
[
{
"_id":"someID1",
"trace":[
{
"latitude":55.629215086862,
"longitude":10.640099246067,
}
]
},
{
"_id":"someID2",
"trace":[
{
"latitude":50.14743798944287,
"longitude":18.52913082363756,
}
]
}
]
奇怪的事情发生了。
只要位置是一个空数组,就会newLocations
毫无问题地绑定到<template dom-repeat="{{locations}}">
元素。但是,如果地图已经显示了几个标记,则旧<google-map-marker>
对象仍然存在,只需添加新对象即可。因此,如果我在document.querySelectorAll('google-map-marker')
更新到 后在开发控制台中执行此操作locations
,我会同时看到newLocations
和oldLocations
。
为了测试数据绑定在<google-map>
元素外应用时是否正常工作,我添加了一个类似的模板。在这里,一切都按预期完美运行:
<template is="dom-repeat" items="{{locations}}" as="user">
<ul>
<li>
<span>{{user._id}}</span>
<ul>
<template is="dom-repeat" items="{{user.trace}}" as="trace">
<li><span>Lat:</span><span>{{trace.latitude}}</span></li>
</template>
</ul>
</li>
</ul>
</template>
以下是到目前为止没有帮助的内容:
- 调用
clear()
GoogleMap 对象。 - 创建绑定到 dom-repeat 模板的第二个属性,但以这种方式访问:
this.splice('_locations',0,this._locations.length);
newLocations.forEach(function(location){
self.push('_locations',location);
});
- 使用单向数据绑定。
- 通过手动删除 DOM 节点
googleMap.removeChild(marker)
并添加它们。好的,这实际上在某种程度上有效,但数据绑定的重点不是您不必这样做吗?
所以,总结一下:<template is="dom-repeat">
谷歌地图内部没有得到关于属性更改的正确通知locations
。<google-map>
谁能告诉我我做错了什么,或者数据绑定在元素内是否不起作用?我是否将事情与 shady / shadow DOM 混为一谈?我是否错误地使用了 dom-repeat 东西?我会失去理智吗?我将不胜感激任何有关解决方案的提示。谢谢!