Activate aurelia canDeactivate() life-cycle hook manually

Viewed 239

I have two types of routes in my application, routes to aurelia app itself and some external routes. I'm using href property to specify external routes. in example below Task is a such external route.

{
    "name": "dashboard",
    "route": "dashboard",
    "moduleId": "../dashboard/dashboard",
    "settings": {
        "icon": "chart-bar",
        "helpPageId": "_30000"
    },
    "title": "routes:root.dashboard",
    "nav": 25
},
{
    "name": "tasks",
    "settings": {
        "icon": "check-square",
        "helpPageId": "_40000"
    },
    "title": "routes:root.tasks",
    "nav": 30,
    "href": "Task"
}

When a user have made some changes in an aurelia route I am using canDeactivate hook to display a custom dialog box to the user, asking to discard changes or save changes.

canDeactivate(): Promise<boolean> {
    //helper method having dialog box logic
    return this.helperMethod.canDiscardChanges(this.modelTracker.isChanged(this.model), this.deactivateSaveCallback.bind(this));
}

But the problem is when I navigate to an external route this hook is not activated. This is understandable because aurelia router is not responsible for that. What I tried to do was bind a method with beforeunload event, and then activate the canDeactivate manually.

async activate(params: any): Promise<void> {
        // some logic
    window.addEventListener("beforeunload", this.onDomWindowBeforenload);
}

onDomWindowBeforeunload: (event: BeforeUnloadEvent) => void = event => {
    this.canDeactivate();
}

async deactivate(): Promise<void> {
    window.removeEventListener("beforeunload", this.onDomWindowBeforeunload);
}

This shows the intended dialog box, but does not wait for user to do anything, it is same as previous, just goes to the specified route after showing the dialog. Any help is appericiated.

0 Answers
Related