Ionic registerBackButtonAction无法工作

7
以下是重现步骤:
  1. Create a basic ionic project ionic start test sidemenu
  2. Add the android platform ionic platform add android
  3. In app.js add the code:

     $ionicPlatform.registerBackButtonAction(function (event) { 
        alert("back button action handler");            
        event.preventDefault(); 
     }, 999);
    

    This code can be added in the .run method or in the $ionicPlatform.ready() method - same result, not working

  4. ionic build android then ionic upload -> or manually put the APK on a device

[错误] - 警报未显示,而是执行了历史视图导航。就像我尝试注册的这个操作没有被考虑一样。

我做错了什么?我在控制器中尝试了这段代码,也尝试了 e.stopPropagation()e.stopImmediatePropagation,但仍然没有成功。

我使用的是最新的Ionic(1.4.5)和Cordova 4.3.0,在一些三星设备上进行了测试。在Ripple中,它可以正常工作。


1
尝试使用document.addEventListener('backbutton', function() {alert('backbutton detected')}, false)监听此事件。 - JimTheDev
1
它可能不起作用,但这是Ionic包装的事件,因此它应该被触发。 - JimTheDev
如果我使用document.addEventListener('backbutton', ......),它可以工作,但是在回调函数中我无法访问ionic服务来检查当前状态名称、检查历史记录、添加条件以执行历史记录中的后退或ionic.Platform.exitApp(),这取决于状态。 - gmodrogan
2
你试过除了999以外的数字吗?比如100?(返回上一个视图) - Ophir Stern
你在.run()函数中是否包含了$ionicPlatform?我按照你的示例做了,它可以正常工作。 - eikooc
显示剩余3条评论
2个回答

4

首先尝试防止默认行为

$ionicPlatform.registerBackButtonAction(function (event) { 
    event.preventDefault();
    alert("back button action handler");  
 }, 999);

代码999也是完全有效的,而代码100、200、300、400、500只是Ionic分配给后退按钮某些操作的优先级。我已经多次使用了优先级900,它只是将您的后退按钮放置在所有其他动作之上。

更多信息请参见文档:http://ionicframework.com/docs/api/service/$ionicPlatform/


0
你能使用代码999吗? 这里有关于100、200、300、400、500的信息,但没有900。 http://ionicframework.com/docs/api/service/$ionicPlatform/
我举例使用了代码501,它可以工作。 这是我的项目的一个示例,它可以工作。
$scope.$on("$ionicView.enter", function () {
            $ionicPlatform.registerBackButtonAction(registerBackButtonAction, 501);
        });

  function registerBackButtonAction(e) {

            if (!!e && typeof e.preventDefault === 'function') {
                e.preventDefault();
            }

            // some code

            return false;
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接