Ionic 2防止硬件后退按钮默认 [英] Ionic 2 prevent hardware back button default

查看:147
本文介绍了Ionic 2防止硬件后退按钮默认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按下硬件后退按钮时,如何防止默认导航?我已经尝试了 registerBackButtonAction ,但它会覆盖我不想要的每个页面中的后退按钮的行为。

How can I prevent default navigation when pressing hardware back button? I've tried registerBackButtonAction, but then it overwrites behavior of back button in every page which I don't want.

这也没有帮助。

document.addEventListener("backbutton", (event) => {
      event.preventDefault();
  }, false);


推荐答案

正如您在 Ionic docs registerBackButtonAction 返回一个函数:

As you can see in Ionic docs registerBackButtonAction returns a function:


一个函数,当被调用时,将取消注册其后退按钮
action。

A function that, when called, will unregister its back button action.

所以你可以使用该函数恢复离开页面时的默认行为,如下所示:

So you can use that function to restore the default behavior when leaving the page, like this:

import { Component} from '@angular/core';

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {

    // Property used to store the callback of the event handler to unsubscribe to it when leaving this page
    public unregisterBackButtonAction: any;

    constructor(...) { ... }

    ionViewDidEnter() {
        this.initializeBackButtonCustomHandler();
    }

    ionViewWillLeave() {
        // Unregister the custom back button action for this page
        this.unregisterBackButtonAction && this.unregisterBackButtonAction();
    }

    public initializeBackButtonCustomHandler(): void {
        this.unregisterBackButtonAction = this.platform.registerBackButtonAction(() => {
            this.customHandleBackButton();
        }, 10);
    }

    private customHandleBackButton(): void {
        // do what you need to do here ...
    }
}

正如您所看到的,关键是存储 registerBackButtonAction的回调方法,稍后在离开页面时使用它(或当你想恢复默认行为时):

So as you can see, the key is to store the callback of the registerBackButtonAction method and use it later when leaving the page (or when you want to restore the default behavior):

this.unregisterBackButtonAction = this.platform.registerBackButtonAction(() => {
    this.customHandleBackButton();
}, 10);

这篇关于Ionic 2防止硬件后退按钮默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆