I am using $ionicPlatform.onHardwareBackButton to use with the Screen Orientation Plugin to change the orientation to portrait when you go back from a view when is playing a Youtube video, here is an example:
app.controller('nameCtrl', ['$ionicPlatform', function('$ionicPlatform') {
$scope.openVideo = function(id) {
var isVideoPlaying = true;
// some stuff here
if(isVideoPlaying) {
$ionicPlatform.onHardwareBackButton(function() {
screen.lockOrientation('portrait');
isVideoPlaying = false;
alert('going back');
});
}
}
}]);
onHardwareBackButton detection works perfect, but when i am not playing a video the callback function is called too. Don’t know why is not working with the boolean part. Any help? Sorry if is an stupid question
Hey, first, this is NOT a stupid question at all and your English is fine. I struggled with this for a while, so don’t feel bad about asking for help.
Now for your issue:
What is happening is everytime you call onHardwareBackButton you create a new event listener. After the user clicks their backbutton, this listener is still active, so unless you deregister it, it will always be listening for the back button event and then its callback is executed on the backButton even. The conditional doesn’t matter, since you already created the listener.
The solution:
To solve this, I would actually use $ionicPlatform.registerBackButtonAction, since it returns a callback you can call to deregister the listener, which means it is called once and then after you deregister it, it will no longer be called.
It looks something like this:
var backButtonListener;
$scope.openVideo = function(id) {
var isVideoPlaying = true;
// some stuff here
if(isVideoPlaying) {
backButtonListener = $ionicPlatform.registerBackButtonAction(function() {
// This will execute once a user clicks their backbutton
screen.lockOrientation('portrait');
isVideoPlaying = false;
alert('going back');
backButtonListener() // Unregisters the backButtonListener you just created
}, 101);
}
}
Also, don’t forget that you should also cleanup any listeners you created in the controller using
$scope.$on('$destroy', function() {
// Deregister any listeners
})
in order to make sure you don’t have them carrying over into other part of your app.
Hey, I noticed I replied with the solution to the OP, who submitted the original question over 2 years ago, but you asked for help just 1 day ago, so in case you still need help, see my solution above and let me know if you need any more help.