Doug Knesek
Doug Knesek

Reputation: 6727

Invoking JavaScript "new" from CoffeeScript

I am trying to reuse a JavaScript library (sim.js) in CoffeeScript code. In an example that comes with sim.js, there are 3 files, "sim-0.26.js", "buffet_restaurant.js", and "buffet_restaurant.html" wired together like this (I've eliminated some parameters to simplify):

Inside of "buffet_restaurant.html", there is

<script type="text/javascript" src="./buffet_restaurant_files/sim-0.26.js"></script>
<script type="text/javascript" src="./buffet_restaurant_files/buffet_restaurant.js"></script>
<script type="text/javascript">
  $(function () {
    $("#run_simulation").click(function () {
      var results = buffetRestaurantSimulation();
...

where buffetRestaurantSimulation is a function inside of buffet_restaurant.js. The code in buffet_restaurant.js starts off like this:

function buffetRestaurantSimulation() 
{
    var sim = new Sim(); 
...

where Sim is defined in sim-0.26.js, like this:

function Sim(){...};

This example runs fine. I want to reuse "Sim" in a CoffeeScript file in node.js. So I try this (invoked from jasmine-node):

sjs = require "./sim-0.26.js"

mysim = new sjs.Sim()

where sim-0.26.js is in the same directory as testsim.spec.coffee, the file containing this code. When I invoke this using:

jasmine-node --coffee ./testsim.spec.coffee

I get this:

mysim = new sjs.Sim();
        ^
TypeError: undefined is not a function

I suspect I am doing a ton of things wrong. I'm pretty new to all this.

Any ideas?

Upvotes: 1

Views: 154

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 160015

Unless Sim is added to exports it will not be available when required - see the docs on modules for more information on the way Node.js modules need to be written.

If this needs to work in both the browser and in node, then simply add this to the code for sim.js:

var root = typeof exports === "object" ? exports : window;

root.Sim = Sim;

Upvotes: 4

Related Questions