onBeforeAction 运行 来不及了

onBeforeAction running too late

我有一个带有助手的页面,该助手依赖于在使用 onBeforeAction 进行路由时设置的 id_sell 变量。当前的问题是助手在设置变量之前运行。

this.route('/chat_id', {
    path: '/chat/:_id',
    template: 'Messages',
    layoutTemplate: 'LayoutMessages',
    onBeforeAction: function() {

      id = Session.get("recipientId");
      id_sell = this.params._id;
      this.next();
       }
    })

如您所见,此 id_sell 变量已在此处设置。

不幸的是我得到了错误

Exception in template helper: ReferenceError: id_sell is not defined

当我的助手试图加载全局变量的值时

如何解决这个加载错误

您可以使用 Session 以便在帮助程序运行之前获取此变量的值。例如,

lib/router.js

Router.route('/chat/:_id', function(){
    Session.set("chatId", this.params._id);
    this.render("chatTemplate", {to:"main"});
});

main.js

这里使用:

var id_sell = Session.get("chatId");

并且在助手运行之前将在此处设置变量。

看来您使用的是 iron 路由器,在这种情况下,您可以将路由定义更改为

this.route('/chat_id', {
    path: '/chat/:_id',
    template: 'Messages',
    layoutTemplate: 'LayoutMessages',
    data: function() {
        return {
            id: this.params._id
        }
   }
})

Messages 模板中,您可以访问 Template.currentData().id 来访问变量。

然后,如果你想从 collection 加载一些东西,你可以将你的路由更改为

this.route('/chat_id', {
    path: '/chat/:_id',
    template: 'Messages',
    layoutTemplate: 'LayoutMessages',
    waitOn: function() {
        return Meteor.subscribe('messages');
    },
    data: function() {
        return {
            id: this.params._id,
            messages: Messages.find({ chatId: this.params._id })
        };
    }
});

然后模板将有 Template.currentData().messages 可用并且 {{#each messages}} 将在 html 中工作。

(显然用您的出版物名称和 collection 替换 messagesMessages)。

最后,您可以将 this.params._id 传递到 Meteor.subscribe(...) 调用中以仅订阅您关心的项目 - 但那是另一回事了。