1

I have a basic cordova app, and when the user presses the back button after filling out a form, I want the form to be saved to localstorage and then the back button to route back to the menu. Saving the form is not an issue, I have this working perfectly. However I can't get the functionality to work when the backbutton is pressed.

function init(){
   document.addEventListener("deviceready", onDeviceReady, false);
   };

This adds for device ready

function onDeviceReady(){
  document.addEventListener("backbutton", onBackKeyDown, false);
}

Then I add the back button event

router.addRoute('#basicInformation', function () {
    $('body').find("#populate").html(new BasicInformationView().render().$el);

    $(":button").click(() => {
        handleBasicForm(false);
    });

    function onBackKeyDown(){
        handleBasicForm(true);
    }

Then here inside of my route I try and handle the onBackKeyDown function that is fired when the back button is pressed.

However the event is not being fired, am I handling this the correct way?

I want to be able to override the back key functionality on each page, that way I can make sure each form saves correctly, and additional pages are handled properly.

  • Looks correct to me, are you sure the event isn't firing? What device are you testing this functionality on? – BShaps Jul 17 '18 at 19:45
  • Tested on both an emulator, and various Android tablets. It takes the user back, but doesn't fire the function – Snow Bezera Jul 17 '18 at 21:07
  • I followed that answer and my code is setup just as they put – Snow Bezera Jul 17 '18 at 22:24
  • As in you made the changes to your code so that the declaration of `onBackKeyDown()` was moved to the line right after the onDeviceReady() function, and made sure all of the suggestions in the comments don't apply to your project? – BShaps Jul 17 '18 at 23:37
  • How would I use the function if it's called right away it? Need to handle it in a route with information specific to it – Snow Bezera Jul 17 '18 at 23:57
  • You can't do event listeners like that in javascript. The function has to be declared and exist in memory before the `document.addEventListener` is called. If you want to change the function called, you'll need to destroy the old event listener and create a new one. – BShaps Jul 18 '18 at 00:19
  • I got the back button to work in a sense using your recommendation, however it only saves half the time, the rest it overwrites it with empty values, however that isn't an issue that pertains to this question so I'm saying this is solved. – Snow Bezera Jul 18 '18 at 02:16

0 Answers0