[英]Meteor.js - how to rerender a template on login
我有一個應用程序,該應用程序在名為“ map”的模板的每個頁面上都有一個傳單地圖。 在該地圖中,我在“ Template.map.rendered”函數中添加了一個上下文菜單。
棘手的地方是,我想在用戶登錄時在該上下文菜單中添加一個斷開鏈接和一個配置文件鏈接,而不是在用戶未登錄時添加一個鏈接。 即使沒有連接,地圖也在那里。
我現在的問題是,當我登錄或注銷應用程序時,我的地圖沒有被渲染。 我嘗試了一些在google上找到的解決方案,但似乎沒有任何效果,我在這里有點迷路。
這是我的第一個流星應用。
碼:
Template.map.rendered = function(){
L.Icon.Default.imagePath = 'packages/leaflet/images';
var map = L.map('map', {
doubleClickZoom: false,
contextmenu: true,
contextmenuWidth: 160,
contextmenuItems: [{
text: 'Show coordinates',
callback: function(event){
console.log(event);
},
icon: 'images/icons/mini-map-pin.png'
}]
}).setView([Session.get('mapLatitude'), Session.get('mapLongitude')], Session.get('mapZoom'));
map.on('dragend zoomend', function(event){
//map position and zoom are saved in session on every action so they
//stay the same when the template is rerendered
Session.set("mapLatitude", map.getCenter().lat);
Session.set("mapLongitude", map.getCenter().lng);
Session.set("mapZoom", map.getZoom());
});
if( Meteor.loggingIn() ){
map.contextmenu.addItem('-');
map.contextmenu.addItem({
text: 'My profile',
callback: function(event){
console.log(event);
},
icon: 'images/icons/profile.png'
});
map.contextmenu.addItem({
text: 'Disconnect',
callback: function(event){
console.log(event);
},
icon: 'images/icons/logout.png'
});
}
L.tileLayer.provider('OpenStreetMap.BlackAndWhite').addTo(map);
}
地圖模板就是這樣
template(name="map")
div#map
登錄名是帶有“ accounts-ui-bootstrap-3”的標准“ account-base”
編輯:啊,如果那改變了我使用的是玉而不是烈焰
您的代碼可能具有競爭條件,因為Meteor.loggingIn()
僅在很短時間內為true,並且僅在該窗口中呈現模板才能顯示菜單項。 此外,正如您所發現的,它不會隨着用戶注銷而再次運行。
我不知道您的地圖插件有什么功能,但是假設它具有添加/刪除功能,您可以嘗試在呈現的函數內部使用自動運行功能,而不是上面的if( Meteor.loggingIn() )
代碼。 嘗試以下操作:
Template.map.rendered = function() {
// create the map for all users
var map = ...;
// replace the if( Meteor.loggingIn() ) section with this code
this.autorun(function() {
if (Meteor.userId()) {
// add code here to add menu items
map.contextmenu.addItem(...);
} else {
// add code here to remove menu items
map.contextmenu.removeItem(...);
}
});
};
這個想法是,它將創建一個反應式計算,該計算將在用戶登錄或注銷時運行。 在每種情況下,您都可以根據需要更新地圖菜單。
設置一個名為“ logged”的會話變量,默認情況下為false,並在登錄時將其設置為true。然后在此會話更改時,在要重新呈現的任何模板中添加“ Session.get(“ logged”),無論何時使用“ Session” “ .get”模板中的流星會創建一個依賴項,並在檢測到依賴項已更改時重新渲染模板。
如果您不想為此使用會話變量,則可以在“ Deps”上的Meteor文檔中閱讀,該文檔用於創建依賴項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.