PRE-REQUISITES

For the following code examples to work, you will need to add Fliplet’s Data Sources API to your app. To add it follow the steps referenced here.

When a user clicks a button to navigate away from the current screen and go to a new screen, you may want to run some code before they do.

One example would be to save some data before the user exits a screen and the data is lost. Or you may want to gather some analytics about how the user is using the app. Ideally, the code should be kept to a minimum to avoid a user experiencing a large lag before the screen transition occurs.

The example below runs some code just before a user leaves the screen.

Fliplet.Hooks.on('beforePageView', function (data) {
  // Enter your custom code here
});

If you’d like to stop or cancel the screen transition, then you can ‘reject’ the request to change screen with the following code (if you don’t reject the request, the screen will change when the code below finishes running).

Fliplet.Hooks.on('beforePageView', function (data) {
  // If you want to stop execution, simply return a promise rejection
  return Promise.reject({ errorMessage: 'Cannot access the Admin area' });
});

The ‘beforePageView’ hook also provides you with some information about the user’s intended destination. The ‘data’ variable can contain the Screen ID. You can find more information here.

In a more detailed example below, we’re using ‘data’ to find out the ID of the intended destination screen. The code then checks if the destination screen ID matches a predefined screen ID (in this case it’s ‘84753’. You can find a screen’s ID by clicking the options in the Screen menu in Fliplet Studio). If the destination screen matches our predefined screen then the navigation request is rejected.

Fliplet.Hooks.on('beforePageView', function (data) {
  // If you want to stop execution, simply return a promise rejection
  if (data.page.id === 84753) {
    return Promise.reject({ errorMessage: 'Cannot access the Admin area' });
  }
});

Another example would be to save data before navigating the user to a new screen.

var dataToBeSaved = {
  name: 'John Smith',
  age: 36
};

Fliplet.Hooks.on('beforePageView', function (data) {
  // If you need an asynchronous processing, like saving data to a datasource
  // You need to return a Promise so that the user is only navigated after the processing is done
  return Fliplet.DataSources.connect(18798)
    .then(function (connection) {
      return connection.insert(dataToBeSaved);
    });
});

Note that in this example, we don’t need to explicitly tell the code to continue the navigation to the next screen. The navigation will simply resume once the code has been run.

However, if your code will take a long time to run (eg: you need to wait for a remote server) then it would be a good idea to inform the user that something is happening eg: by using a toast popup message.

Was this article helpful?
YesNo