1

For a web-app I'm building, I'm really interested in recursing through an object tree and modifying nodes on the fly. There's an underscore mixin that promises that, underscore.loop, but I can't seem to pull it into my page. I get a script error:

Uncaught TypeError: Cannot call method 'mixin' of undefined

which is on line 33 of the tool.

Now, underscore.loop.js is pulled in after backbone.js and underscore-data.js.

  1. Both of these tools use Underscore, and
  2. Underscore is definitely available after trying underscore.loop.

So why can't underscore.loop.js see Underscore. It uses pretty much the same scoping and initialization semantics as underscore-data.js. Can anyone shed any light on this?

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Nutritioustim
  • 2,686
  • 4
  • 32
  • 57

1 Answers1

1

Look a little higher in the source for underscore.loop and you'll see this:

var RecursiveCall, flatStackLoop, _;
var __slice = Array.prototype.slice;
try {
  _ = require('underscore');
} catch (_e) {}

Note the var ... _; and how _ is initialized. So underscore.loop.js is trying to make sure that underscore.js is loaded and that it has a local version of _ to use. require is a node.js-ism so you don't have it in your client-side world and that leaves you with an undefined value in _. You can either grab a client-side library that supplies a node.js compatible require:

or edit your copy of underscore.loop.js to not include the var _; declaration or the try block. Alternatively, you could hack up a little require implementation of your own that just does this:

function require(what) {
    return what == 'underscore' ? window._ : null;
}

or even:

function require(ignored) { return window._ }

and load your require hack between underscore.js and underscore.loop.js.

Community
  • 1
  • 1
mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • 1
    Ho haa, that did the trick. Thanks. Now I just need to figure out how to use the darn thing :) I mostly want to traverse the tree (like in a visitor pattern), find and update nodes on the fly. – Nutritioustim Jan 31 '12 at 06:22
  • 1
    I'm the author of underscore.loop. For any who care to know, I pushed a change that fixes this issue. Should work on its own now. – benekastah Feb 02 '12 at 05:52
  • @benekastah: That's awesome! I love it when people (such as [apneadiving](http://stackoverflow.com/users/350087/apneadiving) and gmaps4rails)use SO as a support forum for their software. – mu is too short Feb 02 '12 at 06:13
  • @muistooshort Agreed! This is the best support forum there is. Why use anything else? – benekastah Feb 02 '12 at 15:01
  • @benekastah I added an underscore.loop.js tag if you want to note the bug fix as an answers for posterity. – mu is too short Feb 02 '12 at 19:17