For code reuse purpose I want to capture some logic in a single function and have it called in other modules
Here is the function definition
// Module A
define (require) ->
doSomething(a, b, c) ->
"#{a}?#{b}&#{c}"
And here is how the funciton doSomething
is used
// Module B
define(require) ->
a = require 'A'
...
class Bee
constructor: ->
@val = a.doSomething(1, 2, 3)
However in the browser, I got this error message
Uncaught ReferenceError: doSomething is not defined
What is the proper way to export/import a free function in coffeescript?
This:
define (require) ->
doSomething(a, b, c) ->
"#{a}?#{b}&#{c}"
isn't a function definition. That is really this in disguise:
define (require) ->
return doSomething(a, b, c)( -> "#{a}?#{b}&#{c}")
so your module is trying to call the doSomething
function and then call what it returns as another function which takes a third function as an argument. Then whatever doSomething(...)(...)
returns is sent back from the module.
So when you say this:
a = require 'A'
you're getting "who knows what" in a
and that thing doesn't have a doSomething
property so a.doSomething(1,2,3)
gives you a ReferenceError
.
I think you want to wrap your function in an object in your module:
define (require) ->
doSomething: (a, b, c) ->
"#{a}?#{b}&#{c}"
Alternatively, you could just return the function:
define (require) ->
(a, b, c) ->
"#{a}?#{b}&#{c}"
and then use it like this:
doSomething = require 'A'
doSomething(1, 2, 3)