Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

registerBackButtonAction , Ionic2 , for different pages

I am developing an Ionic2 app. I am confused with registerBackButtonAction functionality.

I have done this on one page (say pageA). and it is working as expected.

this.platform.registerBackButtonAction(() => {
     console.log("back presed");
    this.abortDownloadAndExit();
    });

Now I want to do some other action on registerBackButtonAction on some other page (sayPageB). But Ionic is taking action from pageA

How can I register different acition on different pages.

like image 688
raju Avatar asked Mar 27 '17 06:03

raju


1 Answers

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

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

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);
like image 172
sebaferreras Avatar answered Nov 18 '22 13:11

sebaferreras