js -如何在登录时呈现模板

Meteor.js - how to rerender a template on login

本文关键字:登录 js      更新时间:2023-09-26

我有一个应用程序与传单地图的每一页在一个名为"地图"的模板。在这个地图中,我在"Template.map"中添加了一个上下文菜单。呈现"功能。

它变得棘手的地方是,我想在该上下文菜单中添加一个断开链接和一个配置文件链接,当用户登录时,而不是当用户不是。即使你没有连接,地图也在那里。

我现在的问题是,当我登录或注销应用程序时,我的地图没有重新渲染。我尝试了几个解决方案,我在谷歌上找到的,但似乎没有工作,我有点迷路了。

这是我的第一个流星应用。

代码:

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

和登录是标准的"account-base"与"accounts-ui-bootstrap-3"

编辑:啊,我用翡翠代替火焰,如果这改变了什么

很可能您的代码有竞争条件,因为Meteor.loggingIn()只会在很短的时间内为真,并且模板必须仅在该窗口中呈现,以便菜单项显示。此外,正如您所发现的,当用户注销时,它将不会再次运行。

我不知道你的地图插件有什么能力,但假设它有添加/删除功能,你可以尝试在你的渲染函数中使用自动运行,而不是上面的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。流星创建一个依赖项,并在检测到依赖项发生更改时呈现该模板。

如果你不想为此使用会话变量,你可以在Meteor文档中的"Deps"中阅读,它用于创建依赖。