Ionic cancel hard BACK button override

2019-02-25 08:00发布

There are questions about overriding the physical Android BACK button in Ionic, to provide custom behaviour:

But how do you cancel the override to restore default behaviour?


I have tried changing the priority of the handler, in the hope that a default handler may have a higher priority.

var customBackButton = function() {
    console.log("this is custom behaviour");
};
$ionicPlatform.registerBackButtonAction(
    customBackButton, 101
);
$scope.$on('$destroy', function() {
    $ionicPlatform.registerBackButtonAction(
        customBackButton, 0
    );
});

This does not work.


1条回答
Animai°情兽
2楼-- · 2019-02-25 08:37

Ionic v1 solution (out of date)


According to the Ionic docs for $ionicPlatform, the registerBackButtonAction() returns:

A function that, when called, will deregister this backButtonAction.

This can be seen in the code for registerBackButtonAction():

  // return a function to de-register this back button action
  return function() {
    delete self.    [action.id];
  };

So the correct way to deregister / cancel the custom behaviour is to call that function when the controller is destroyed:

var customBackButton = function() {
    console.log("this is custom behaviour");
};

// registerBackButtonAction() returns a function which can be used to deregister it
var deregisterBackButtonAction = $ionicPlatform.registerBackButtonAction(
    customBackButton, 101
);

$scope.$on('$destroy', function() {
    deregisterBackButtonAction();
});

A more complete example showing how to override & restore the hard and soft buttons can be found here:

查看更多
登录 后发表回答