Search code examples
javascriptrequirejsamd

RequireJS define callback returning wrong module dependencies


I'm having a very strange and frustrating problem with RequireJS. When I call require for a module with a list of dependencies, all dependencies available in the callback reference a single module. This is probably easier to explained with code:

Including require.js script (with no data-main attribute)

<script type="text/javascript" src="/js/common/require.min.js" ></script>

Below that I include require my main.js (used in all pages of the site) which in the callback requires my page specific js.

<script type="text/javascript">
  require(['/js/require/main.js'], function () {
    require(['page/home_page']);
  });
</script>

main.js

requirejs.config({
  baseUrl: 'js/require'
});

requirejs(['base'],
function() {
  var base = require('base');
  base.init();
});

home_page.js

define(['home','searchbar'], function (home,searchbar){

  console.log(home.init == searchbar.init); // This is always true !!!

  home.init();
  searchbar.init();
});

home.js

define(function(){
  this.init = function(){
    console.log('in home page'); 
  }
  return this;
});

searchbar.js

define(function(){
  this.init = function(){
    console.log('Now in the searchbar init')
  }
  return this;
});

The issue is in home_page.js both modules home and searchbar reference the same thing. What's strange is that now that I've simplified this example, it seems pretty random which one it chooses. Most times it's searchbar but every few refreshes it will be home.

Anyone have an ideas? Is it something terribly obvious?

EDIT: Simplified example and provided all module source.


Solution

  • You are assigning to this in both modules. This is not a good idea (excuse the pun). this will possibly be the window object in both cases. You could check by adding a

    window.init === searchbar.init
    

    test.

    Rewrite the modules to return unique objects, like so:

    define(function() {
        return {
            init: function() {
                console.log('in home page'); 
            }
        };
    });
    

    and

    define(function() {
        return {
            init: function() {
                console.log('Now in the searchbar init'); 
            }
        };
    });