DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

超链接中data-toggle属性使用新的Session


如果在超链接中将"data-toggle"属性设为"modal",如下所示,则超链接所指向的窗体将使用新的Seesion。

<a href="/register" data-toggle="modal">注册新帐号</a>

比如我们想在每次跳转后将当前url记录在Session变量"currentUrl"中, 但是在url以"login"和"register"结尾时不更新"currentUrl":

Router.onAfterAction(function(){
  if (! (Router.current() && Router.current().url) ) {
    return;
  }
  var currentUrl = Router.current().url;
  if ( (currentUrl.indexOf('login') < 0 ) &&
        currentUrl.indexOf("register") < 0 ) {
    Session.set("currentUrl", currentUrl);
  }
});

然后在登录或者注册成功后取出这个缓存的变量,利用callback函数跳转回之前的页面:

Accounts.createUser({
  email: t.find("#userEmail").value,
  password: t.find("#userPwd").value,
  profile: {
    nickname: t.find("#userNickname").value,
    role: userRole.value,
    gender: gender.value,
    desc: userDesc
  }
}, function(error) {
  if (error) {
    alert("something wrong, registration failed.");
  } else {
    alert("注册并登录成功!");
    var currentUrl = Session.get("currentUrl");
    var tmp = document.createElement('a');
    tmp.href = currentUrl;
    var currentPath = tmp.pathname + tmp.search;
    Router.go(currentPath);
  }
});

那么当点击上面的超链接时,所有Session对象都被清空,"currentUrl"值变为"undefined", 如果用Session.setDefault("currentUrl", "aabb");设置默认值, 则点击上面的超链接后"currentUrl"值变为"aabb", 然后再执行Router.onAfterAction中的callback函数。

这样前面利用缓存变量跳转回原来页面的设计就失效了,页面跳转到"/undefined"页面, 解决办法很简单:去掉超链接中的data-toggle属性,变为一个普通超链接:

<a href="/register">注册新帐号</a>


Published

Feb 18, 2015

Last Updated

Feb 18, 2015

Category

Tech

Tags

  • html 9
  • meteor 47
  • session 4

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor