Search code examples
javascriptdojojs-amd

Why is the Simplified CommonJS Wrapper syntax not working on my Dojo AMD module?


Im starting to sort of wrap my head around requirejs and the new Dojo AMD structure, but I have a problem with some early tests:

cg/signup.js:

define(['dojo/_base/fx', 'dojo/dom'], function(fx, dom){    
    return function(){
        this.hidePreloader = function(id){
            var preloader = dom.byId(id);
            fx.fadeOut({node : preloader}).play()
        }
    }
})

This works fine. In the master cg.js file:

require(['dojo/_base/kernel', 'dojo/_base/loader'])
dojo.registerModulePath('cg', '../cg')

require(['cg/signup', 'dojo/domReady!'], function(Signup){
        var sp = new Signup();
        sp.hidePreloader('preloader')
})

Bam. Done. However, in using the Simplified CommonJS Wrapper structure:

define(function(require){    
    var fx = require('dojo/_base/fx'),
        dom = require('dojo/dom');

    return function(){
        this.hidePreloader = function(id){
            var preloader = dom.byId(id);
            fx.fadeOut({node : preloader}).play()
        }
    }
})

I get an undefinedModule error. It seems to come from the dojo/_base/fx line, but I don't know why.

UPDATE

For clarification.

index.html scripts

<script type="text/javascript" src="js/dojo/dojo.js.uncompressed.js" data-dojo-config="isDebug:true,async:true"></script>
<script type="text/javascript" src="js/cg.js"></script>

cg.js

require(['dojo/_base/kernel', 'dojo/_base/loader'])
dojo.registerModulePath('cg', '../cg')

require(['cg/signup', 'dojo/domReady!'], function(signup){
    signup.testFunc()
})

js/cg/signup.js

define(['require', 'exports'], function(require, exports){
    var dom = require('dojo/_base/kernel');
// Any other require() declarations (with very very few exceptions like 'dojo/_base/array throw undefinedModule errors!!!

    // without any error causing requires, this works fine.
    exports.testFunc = function(){
        alert("hello")
    }
})

Solution

  • dojo completely supports the Simplified CommonJS Wrapper format. however, there is a precondition... you must have no dependencies array.

    define(function (require, exports, module) {
        var fx = require('dojo/_base/fx'),
            dom = require('dojo/dom');
    
        // continue...
    });
    

    this will NOT work the same

    define(['require', 'exports', 'module'], function (require, exports, module) {
        var fx = require('dojo/_base/fx'),
            dom = require('dojo/dom');
    
        // continue...
    });
    

    nor will this...

    // in this case require, exports and module will not even exist
    define([], function (require, exports, module) {
            var fx = require('dojo/_base/fx'),
            dom = require('dojo/dom');
    
        // continue...
    });