[英]Javascript/AngularJS - Wait for a callback to finish executing
I have a service called Progress
with a method called confirmation
that takes Progress.confirmation(message, accepted, rejected)
; 我有一个名为Progress
的服务,该服务带有一种名为confirmation
的方法,该方法接受Progress.confirmation(message, accepted, rejected)
;
So far the function is: 到目前为止,该功能是:
if (!_.isString(message)) {
console.warn('No confirmation message was provided');
return false;
}
$rootScope.confirmation.message = message;
$('#confirmation').foundation('reveal', 'open');
// User confirms. If accepted() is provided, then run it
$rootScope.confirmationAccept = function() {
if (_.isFunction(accepted)) accepted();
$('#confirmation').foundation('reveal', 'close');
};
// User confirms. If rejected() is provided, then run it
$rootScope.confirmationReject = function() {
if (_.isFunction(rejected)) rejected();
$('#confirmation').foundation('reveal', 'close');
};
The two functions $rootScope.confirmationAccept()
and $rootScope.confirmationReject()
are just a check/cancel button in the confirmation reveal page. $rootScope.confirmationAccept()
和$rootScope.confirmationReject()
这两个函数只是确认显示页面中的检查/取消按钮。
What I want to do is to wait for accepted()
/ rejected()
to execute before I close the reveal page. 我想要做的是在关闭显示页面之前等待accepted()
/ rejected()
执行。 How can I do this? 我怎样才能做到这一点?
Since I am passing the two functions, I can't really rely that the person coding will remember to use a $q
defer, so I don't think that would be an option? 由于我传递了这两个函数,因此我不能真正依靠编码人员记住使用$q
延迟,因此我认为这不是一个选择吗? Also, I can't rely that the callbacks will return a values, so I can't wait/watch for a returned value. 另外,我不能依靠回调函数返回值,所以我不能等待/观察返回的值。
Thanks 谢谢
您可以使用$ broadcast收听更改吗?
It is not really clear what your asking. 目前还不清楚您的要求是什么。
This really should be a directive. 这确实应该是一个指令。 Your confirmation modal case above should be straight forward to make a directive so you don't have magic dom manipulation or rootscope pollution. 您上面的确认模态案例应该直接做出指示,这样您就不会受到魔法dom操纵或Rootscope污染。
Typically you would encapsulate this logic in a directive like the following: 通常,您会将这种逻辑封装在如下指令中:
<confirm-modal open="confirmationOpen" success="successCb()" abort="abortedCb" custom-message="'myCustomMessage'">
<button ng-click="launchConfirmation()">Click me or launch from controller</button>
This lets your controller manage the state. 这使您的控制器可以管理状态。
$scope.launchConfirmation() {
$scope.confirmationOpen = true;
}
$scope.successCb() {
//They Confirmed
//Do Async stuff
myAsync().then(function() {
$scope.confirmationOpen = false;
});
}
$scope.abortCb = function() {
//nothing async here
reset();
$scope.confirmationOpen = false;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.