[英]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.