0

I'm modularizing my client-side JavaScript code with Browserify.

In my "page" module, I'm trying to export an object with methods, like so:

// page.js

exports.picker = {
    init: function () { ... },
    getValue: function () { ... },
    // etc.
};

However, in another module, when I try to use one of these methods, I get a TypeError:

// other module

var page = require('./page');

// later...
page.picker.init(); // throws "TypeError: page.picker is undefined"

Not sure what I'm doing wrong. Is it maybe because I'm exporting an object instead of a function?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • No, objects should be fine. Does it actually work if you use a function instead of the object literal? – Bergi Sep 29 '14 at 00:32
  • The code works as given (after dropping the `...`s and trailing `,` in `page.js`). Try writing a minimal example that exhibits the problem. – Aaron Dufour Sep 29 '14 at 00:36
  • @Bergi No. Probably a n00b question, but does it matter if page.js also requires that other module (i.e. both modules require each other)? I have several such two-way dependencies in my modules. Could that be the issue? – Šime Vidas Sep 29 '14 at 01:01
  • Yes, it definitely is. You can usually avoid the issue by requiring one of them not from the module definition code, but directly inside a method that is only executed later. I'm not sure how node.js and how browserify do handle *circular dependencies* exactly, though. – Bergi Sep 29 '14 at 01:06
  • @Bergi Thanks, sounds like a plan. Another solution *could* be callbacks. (Currently I have module A invoke a method of module B, which then runs some code and after that invokes a method of module A in return. Instead, I could have A invoke a method of B and pass a callback via arguments. Then when B has run its code, it just invokes A's callback instead of having to invoke A's method directly.) – Šime Vidas Sep 29 '14 at 01:13
  • Are you also adding anything else to the exports? Anyway, try module.exports.pager – Zlatko Sep 29 '14 at 14:27

0 Answers0