Skip to content

Using curl.js with underscore

unscriptable edited this page Apr 26, 2012 · 10 revisions

Using curl.js with underscore

The creators of underscore are still deciding whether to incorporate full AMD support or not. (Update: they seem to have decided to embrace the 1990's and ripped it out again.) In the meantime, you can use an AMD-aware version at the amdjs maintained fork.

(Don't want to use the amdjs fork? Scroll to the bottom of this page.)

Better still, use Lo-Dash. It's smaller and up to 8x faster than underscore, despite having the same API.

You must map the path to underscore.js when configuring curl.js.

underscore registers itself as an absolutely named module. curl.js (as well other AMD loaders) ensures that the correct module got loaded by comparing the id of the requested module with the module that was actually loaded. Since underscore registers itself with the name, "underscore", all modules that list underscore as a dependency must also refer to it by the exact same name. Trying to refer to underscore as any of the following module ids will fail:

  • "js/documentcloud/underscore/underscore" (BAD: path is included)
  • "Underscore" (BAD: capitalization is different)
  • "underscore.1.3.1.min" (BAD: extra filename bits)

The best way to ensure all code can correctly refer to it as "underscore", you should add the following path mapping to curl.js's config:

paths: {
	"underscore": "js/documentcloud/underscore/underscore.1.3.1.min"
}

For more information about paths, see Understanding Paths.

For more hints about using underscore, check out the Using curl.js with jQuery page. Much of the information on that page applies to underscore, as well.

Using underscore as a plain, non-AMD javascript file

There is a way to use underscore without "wrapping" it in an AMD define(). Simply use the js! plugin and use the !exports=_ suffix. Like this:

curl(['js!path/to/underscore!exports=_'], function (_) { // use _ here! });

Also, since underscore supports CommonJS-like environments, you can use curl.js's ability to load Unwrapped CJS modules (scroll down). This requires more config settings and is a bit slower since curl.js has to scan the file.