0

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.

2
  • Is that your full requirejs.config? Can you show the searchbar, home and account module files? Commented Apr 25, 2013 at 6:34
  • @PaulGrime, question has been modified Commented Apr 25, 2013 at 21:55

1 Answer 1

2

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'); 
        }
    };
});
Sign up to request clarification or add additional context in comments.

1 Comment

Blah, yep, that's what it was. Don't know why but I thought the callbacks might have their own scope.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.