0
votes

I'm trying to dynamically load custom modules based on a data attribute. It's almost working perfectly but for some reasons my module is called twice with different paths and I can't figure why.

My project structure looks like that:

+ Assets
    + js
        • main.js
        + libs
        + modules
            • mod.env.js
            • mod.utils.js
            • mod.session.js
        + plugins
        + views
            • signup.js
            • login.js
            • home.js

In my main.js file I have some basic configuration:

require.config({
    baseUrl: '/Assets/js',

    paths: {
        // Libs
        'jquery'    : 'libs/jquery/jquery-2.0.3.min',

        // Module for the project
        'env':           'modules/atmco.env',
        'utils':         'modules/atmco.utils',
        'session':       'modules/atmco.session'
    }
});

Still in the main.js file is where I put the logic for the conditial loading of the modules:

require(['require', 'jquery','env'],
  function ( require, $, env ) {
      'use strict';

      function init() {
          // Grab the modules/pages on the data attribute of the body
          var modules = $('body').data('modules') || '';
          var pages = $('body').data('page') || '';

          // Initialize the environment stuff for your project
          env.initEnv();

          if ( pages ) {
              require(['./views/' + pages.toLowerCase().split(/\s*,\s*/)[0]]);
          }
      }

      // Initialize the application when the dom is ready
      $(function () {
          init();
      });
  }
);

My page has the right attributes (<body data-page="Signup" data-module="">) but for some reasons requirejs tries to call 2 different files: requirejs error

  • The custom module is called as expected "/Assets/js/views/signup.js"

  • Then it tries to call "/Assets/js/signup.js" which doesn't exists

Finally, here's a look at how I define my custom module, including the custom name. It seems pretty basic:

define('view/signup',
    ['utils'],
    function ( utils ) {
        console.log('my module' + utils.lang );

        return {
        };
    }
);

If anyone could point me to my mistake it would really help me with my app and understanding better how requirejs works. Thanks a lot!

1
Try require(['views/' + pages.toLowerCase().split(/\s*,\s*/)[0]]); instead of require(['./views/' + pages.toLowerCase().split(/\s*,\s*/)[0]]);.Sirko

1 Answers

0
votes

Found the solution:

Naming (or naming in fact) the module was actually messing the module definition. Therefor I just needed to adjust the code to:

define(
    ['utils'],
    function ( utils ) {
        console.log('my module' + utils.lang );

        return {
        };
    }
);

This question really helped me out figuring it: Requirejs function in define not executed