single-page-applicationdurandal-2.0

How to call global function on route change within Durandal?


Given the following scenario for our Durandal application:

When a customer visits certain URL's of our SPA we would like to present him a dialog/pop-up. For the initial load this is not a problem, we call a function from the activate callback function in the shell.js.

The problem is when the user navigates through our site and reaches a certain URL where the dialog should pop up.

Let say we've two viewmodels product and prodcutOverview and the shell. All three would have an activate function like this:

vm.activate = function () {
    var keywordsExists = checkUrl();
    if(keywordsExists){
       globals.showDialog();
    }
};

The idea of globals comes from this question

How do I create one activate function that is used on every route change so I prevent the duplicate code on my viewmodels?


Solution

  • You could create the common activate function as a require module and then reuse it in that manner.

    define('common-activate', ['globals'], function(globals){
       function checkUrl(){
          //checks url
       }
       var activate = function(){
          var keywordsExists = checkUrl();
          if(keywordsExists){
          globals.showDialog();
       }
       return activate;
    }
    
    define('products', ['common-activate'], function(activate){
       return {
          activate: activate
       };
    }
    
    define('productOverview', ['common-activate'], function(activate){
       return {
          activate: activate
       };
    }