转到特定路线时会话变量未更新

Session variable not updating when going to a specific route

我在设置会话变量和处理路由器时做错了

main.js:

Template.global.onCreated(function(){
    Session.setDefault("musicFilteredCategory", "latest")
});

router.js:

Router.route("/music/:category?", {
    name: "music",
    template: "music",
    beforeAction: function () {
        var category = this.params.category;
        Session.set("musicFilteredCategory", category);
    }
});

但是当我打开页面“/music/latin-radio”并检查 Session.get("musicFilteredCategory") 时,我得到的是 "latest" 而不是 "latin-radio"

后来我把Session.setDefault("musicFilteredCategory","latest")改到Template.global.onCreated({})外面,结果还是一样

执行此操作的最佳做​​法应该是什么?

修复后我还想添加此功能: 当用户转到“/music”时被重定向到“/music/:defaultMusicCategory”

PS:我正在使用 Meteor 1.2.0.1 和 Iron Router 1.0.9

正如@Kyll 指出的那样,我应该将 onBeforeAction 用于 运行.

的函数

这解决了我的部分问题,但是在访问不同的路由时类别没有改变。

这是我必须做的:

Router.route("/music/:category?", {
    name: "music",
    template: "music",
    onBeforeAction: function () {
        var category = this.params.category;
        if (category !== "undefined") {
            Session.set("musicFilteredCategory", category);
        }
        this.render("music");
    }
});

这不包括路由“/music”(没有斜杠)所以我也不得不添加这条路由,我把它放在上面的代码之前

Router.route("/music", {
    name: "music",
    template: "music"
});

为了解决这个问题,我不得不将 Session.setDefault() 移到模板范围之外,因为它们覆盖了在路由器上建立的会话,所以我不得不将它们放在 Meteor.startup 函数中

Meteor.startup(function () {
    Session.setDefault("musicFilteredCategory", "latest");
});