简体   繁体   中英

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) ;

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.

What I want to do is to wait for accepted() / rejected() to execute before I close the reveal page. 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? 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.

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;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM