Is there an alternative way to share logic between views?

I have an existing app that’s very large and migrating it to TS isn’t feasible for me right now. On top of that, my app.js is becoming very big and hard to manage. Is there any other option for sharing logic between views?

Yes, it is possible to require shared code/logic in a JS app. In order to do so, please follow the steps below:

  1. Add the following to your app.js (Shared JS file). This defines the require statement in the JourneyApps runtime of a JS app.
// BEGIN REQUIRE
var modules = {};
var module = null;

function require(moduleName) {
    var previousModule = module;

    if (moduleName in modules) {
        return modules[moduleName];
    }

    if (!(moduleName in __modules)) {
        throw new Error("Cannot find module: " + moduleName);
    }

    module = {
        id: moduleName,
        exports: {}
    };
    try {
        var moduleThis = {};
        modules[moduleName] = module.exports;
        __modules[moduleName].call(moduleThis);
        modules[moduleName] = module.exports;
        return modules[moduleName];
    } finally {
        module = previousModule;
    }
}
// END REQUIRE 
  1. Create a new view and place it in a view directory that will store the shared js modules e.g. lib/user_module

  2. Write some code in the new view JS. Note: At the time of writing this, one cannot create modular view components, so you can only export and require JavaScript functions e.g.

var UserModule = {
    /**
    * Get an instance of a User by ID. Throws an error if not found.
    * @param {string} id
    * @returns {DB.user}
    */
    Get: function (id) {
        var user = DB.user.first();
        if(!user) throw new Error("User with ID: " + id + " not found in the database");
        return user;
    }
}

module.exports = UserModule;
  1. Require your new module by specifying the path to the module in an existing view where you want to implement the functions e.g.

View XML:

<?xml version="1.0" encoding="UTF-8"?>
    <param name="user" type="user"/>
</view>

View JS:

var UserModule = require("lib/user_module");

function init () {
    var user = UserModule.Get(view.user.id);
    console.log(user.id);
}
1 Like