0
我有一個模板在我的流星應用程序中顯示地圖。這個模板用於兩件事情:使用與meteor.js中的不同數據相同的模板
- 顯示我的應用程序的地圖
- 顯示,一旦用戶選擇了特定場地的個體位置上的搜索結果的一個
目前我的代碼下面的(我有一個關於這個模板沒有其他功能或輔助):
Template.map.rendered = function() {
if(!map)
var map = new Course_map('#map');
Deps.autorun(function(){
if (Session.get("current_place")){
var places = Places.find(Session.get("current_place")).fetch();
}
else{
var places_cursor = get_searched_places();
if (places_cursor){
var places = places_cursor[0].fetch();
var places_id = _.pluck(places,'_id');
//Remove the markers that are no longer in the places_id array
map.remove_markers(places_id);
}
}
if(places){
// Add all the marker in places
for(var i = 0, places_length = places.length; i < places_length; i ++){
map.add_marker(places[i]);
}
// Recenter the map to focus on the marker area
map.calc_bounds();
}
});
};
我的地圖模板:
<template name="map">
<div id="map" class='google-map'>
</div>
取決於用戶是否選擇一個地方與Session.get(「current_place」)我加載在我的地方變量不同的信息。
我不太喜歡那種設計,我想我可以找到一種更好的方式來做我想做的事情。你有什麼建議嗎 ?
@Itbesh您的解決方案看起來好像沒什麼問題。我唯一不喜歡的就是'map'變量的定義。我想你需要使用'this.map'(甚至是'this._map',見[here](http://docs.meteor.com/#template_inst)),因爲你一定要將這個對象附加到你的模板中instacne,而不是本地範圍。我對嗎? –
@ Tomasz:感謝您的評論。我編輯我的帖子以顯示我的模板,並精確地表示渲染代碼是此模板的唯一代碼。所以不,我不使用this.map我創建了這樣的地圖,因爲我需要一張地圖,否則你會怎麼做? – ltbesh
從你所說的話我假設你需要從你的代碼中的其他地方訪問這個'map'對象,所以它可能是全局定義的,對嗎?那麼你爲什麼使用'var'前綴?請注意,前綴爲'var'的變量只能在本地定義,所以您的全局'map'保持不變,並且條件'if(!map)'實際上始終滿足。所以實際上你在每個'render'事件上創建一個'Course_map'的新實例,但我認爲這不是你想要的。 –