【问题标题】:Meteor iron:router routecontroller change context of thisMeteor Iron:router routecontroller 改变 this 的上下文
【发布时间】:2015-12-12 09:09:46
【问题描述】:

我有一个检查用户是否登录的函数,它看起来像这样:

var requireLogin = function () {
    if (! Meteor.user()) {
        if (Meteor.loggingIn()) {
            this.render(this.loadingTemplate);
        } else {
            this.render('accessDenied');
        }
    } else {
        this.next();
    }
};

这是一个简单的功能,当我在这样的钩子上使用它时它就可以工作:

Router.onBeforeAction(requireLogin, {only: 'postSubmit'});

但是,当我尝试在这样的扩展路由控制器中调用它时:

LogInController = RouteController.extend({
    onBeforeAction: function () {
        requireLogin();
    }
});

它不起作用。但是我可以将函数的上下文粘贴到登录控制器中的 onBeforeAction 中,它会起作用。

LogInController = RouteController.extend({
    onBeforeAction: function () {
        if (! Meteor.user()) {
            if (Meteor.loggingIn()) {
                this.render(this.loadingTemplate);
            } else {
                this.render('accessDenied');
            }
        } else {
            this.next();
        }
    }
});

所以我需要做什么?我需要将 this 的值传递给 requireLogin 函数还是有更聪明的方法?

【问题讨论】:

    标签: meteor routes this iron-router


    【解决方案1】:

    我相信你可以通过使用javascript的bind函数来解决这个问题,它将函数绑定到上下文:

    LogInController = RouteController.extend({
        onBeforeAction: function () {
            requireLogin.bind(this)();
        }
    });
    

    但是,如果您只是将函数作为值直接传递,那么这甚至可能没有必要,从而避免可能导致上下文更改的重定向:

    LogInController = RouteController.extend({
        onBeforeAction: requireLogin
    });
    

    【讨论】:

    • 感谢克里斯蒂安的回复。我已经尝试直接传递函数,但出现语法错误。我不知道绑定功能。非常感谢。
    猜你喜欢
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多