Meteor.js – 如何在login时重新渲染模板

我有一个名为“地图”的模板中的每个页面上的传单地图的应用程序。 在那张地图中,我在“Template.map.rendered”函数中添加了一个contextmenu。

在哪里变得棘手,是我想在用户login时在该上下文菜单中添加断开链接和configuration文件链接,而不是在用户没有login时添加。 即使你没有连接,地图也在那里。

我现在的问题是,当我login或注销应用程序时,我的地图不会被重新渲染。 我尝试了几个我在谷歌上find的解决scheme,但似乎没有任何工作,我在这里有点失落。

这是我的第一个meteor应用程序。

码:

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 

login是标准的“account-base”与“accounts-ui-bootstrap-3”

编辑:啊,我用翡翠,而不是火焰,如果改变的东西

您的代码可能有一个竞争条件,因为Meteor.loggingIn()只会在短时间内为true,并且只能在该窗口中呈现模板才能显示菜单项。 而且,正如您发现的那样,用户注销后不会再运行。

我不知道你的地图插件能够做什么,但假设它具有添加/删除function,你可以尝试在你的渲染函数中使用自动运行 ,而不是上面的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(...); } }); }; 

这个想法是,它将创build一个反应计算,无论用户login还是退出,都将运行。 在任何情况下,您都可以根据需要更新地图的菜单。

设置一个名为“logged”的会话variables,默认情况下为false,login时将其设置为true,然后在任何模板中添加“Session.get(”logged“),当这个会话发生变化时, .get“模板内Meteor创build一个依赖关系,并在检测到依赖关系发生变化时重新展现模板。

如果您不想使用会话variables,则可以在Meteor文档中读取用于创build依赖关系的“Deps”。