cujojs / curl

curl.js is small, fast, extensible module loader that handles AMD, CommonJS Modules/1.1, CSS, HTML/text, and legacy scripts.
https://github.com/cujojs/curl/wiki
Other
1.88k stars 216 forks source link

define with return in callback function is not returning an object #167

Closed jcollum closed 11 years ago

jcollum commented 11 years ago
(function (name, definition) {
  if (typeof module != 'undefined') {
    console.log("path A");
    module.exports = definition();
  }
  else if (typeof define == 'function' && typeof define.amd == 'object') {
    console.log("path B");
    console.log(definition);
    define(name, [], definition);
  }
  else {
    console.log("path C");
    this[name] = definition();
  }
}('mod', {
      sayHi:function (name) {
        console.log('Hi ' + name + '!');
      }
    }
));

I've gotten that loaded in my client side. I'm expecting to be able to do this:

`modA = define(['mod'], function(mod) { return mod;  }); `

but modA is undefined.

However I can do this:

curl(['mod'], function(mod) { window.greeter = mod; });

and window.greeter is an object with a sayHi function. To be fair, the docs don't really describe using define in this way, but this blog post http://davidwalsh.name/curljs makes me think that it is possible. This seems like something I should be able to do without using the window object. Asked someone about it on SO here: http://stackoverflow.com/a/14869875/30946 and he seemed to think doing it with modA = define ... would work.

Tried this as well: mod = require(['mod'], function(mod){return mod;});

This might be me just not understanding how curl works. If that's the case, maybe it would be helpful to make a best practices section on the wiki? It's not clear how to build an object using things that have been loaded with curl.

unscriptable commented 11 years ago

Hello @jcollum, you may be confusing define with require. define allows you to create a module. require allows you to consume it. curl is a convenient global for bootstrapping your app's main modules. Once your app's main modules are loaded, you can gain access to their dependencies via either define or require:

// "normal" AMD syntax
define(['myApp/dep1', 'myApp/dep2', 'myApp/dep3'], function (dep1, dep1, dep3) {
    // inside here dep1, dep2, and dep3 are resolved references to dependent modules
});
// AMD, but with the CommonJS Modules flavor via injected `require`
define(function (require) {
    var dep1 = require('myApp/dep1');
    var dep2 = require('myApp/dep2');
    var dep3 = require('myApp/dep3');
});

When using modules (AMD, CommonJS, or forthcoming ES6), you should write all of your code inside modules.

I hope this helps.

-- John

unscriptable commented 11 years ago

Closing this. Feel free to reopen it or start a discussion on #cujojs on freenode or here if you have further questions!