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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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.
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: That's awesome! I love it when people (such as apneadiving and gmaps4rails)use SO as a support forum for their software.
@muistooshort Agreed! This is the best support forum there is. Why use anything else?
@benekastah I added an underscore.loop.js tag if you want to note the bug fix as an answers for posterity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.