Reputation: 6171
Start with your module, utils.coffee:
exports.foo = ->
exports.bar = ->
Then your main file:
utils = require './utils'
utils.foo()
foo() and bar() are functions you'll be calling frequently, so you:
foo = require('./utils').foo
bar = require('./utils').bar
foo()
This approach works when only a few functions are defined in the module, but becomes messy as the number of functions increases. Is there a way to add all of a module's functions to your app's namespace?
Upvotes: 4
Views: 5796
Reputation: 67890
Use extend
(with underscore or any other library that provides it. Write it yourself if necessary):
_(global).extend(require('./utils'))
Upvotes: 11
Reputation: 1166
If you don't want to use underscore, you could simply do:
var utils = require('./utils')
for (var key in utils)
global[key] = utils[key]
Upvotes: 6
Reputation: 628
Another way to exports all modules function to global scope like so: Application Module:
(()->
Application = @Application = () ->
if @ instenceof Application
console.log "CONSTRUCTOR INIT"
Application::test = () ->
"TEST"
Version = @Version = '0.0.0.1'
)()
Main App:
require './Application'
App = new Appication()
console.log App.test()
console.log Version
Upvotes: 1
Reputation: 628
something like that is a good approach to my opinion:
utils.coffee
module.exports =
foo: ->
"foo"
bar: ->
"bar"
main.coffee
util = require "./util"
console.log util.foo()
Upvotes: 0
Reputation: 39231
Is there a way to add all of a module's functions to your app's namespace?
No. This is, to my knowledge, the best you can do (using CS' destructuring assignment):
{foo, bar, baz} = require('./utils')
Upvotes: 3