Meteor iron:router routecontroller 改变上下文
Meteor iron:router routecontroller change context of this
我有一个检查用户是否登录的功能,它看起来像这样:
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 函数还是有更聪明的方法?
我相信您可以使用 javascript 的 bind
函数解决这个问题,该函数将函数绑定到上下文:
LogInController = RouteController.extend({
onBeforeAction: function () {
requireLogin.bind(this)();
}
});
但是,如果您直接将函数作为值传递,那么这甚至可能不是必需的,从而避免可能导致上下文更改的重定向:
LogInController = RouteController.extend({
onBeforeAction: requireLogin
});
我有一个检查用户是否登录的功能,它看起来像这样:
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 函数还是有更聪明的方法?
我相信您可以使用 javascript 的 bind
函数解决这个问题,该函数将函数绑定到上下文:
LogInController = RouteController.extend({
onBeforeAction: function () {
requireLogin.bind(this)();
}
});
但是,如果您直接将函数作为值传递,那么这甚至可能不是必需的,从而避免可能导致上下文更改的重定向:
LogInController = RouteController.extend({
onBeforeAction: requireLogin
});