Skip to content

Instantly share code, notes, and snippets.

@arsatiki
Created January 23, 2014 06:54
Show Gist options
  • Save arsatiki/8574116 to your computer and use it in GitHub Desktop.
Save arsatiki/8574116 to your computer and use it in GitHub Desktop.
Hack to load elm code into node.js. Requires path to Elm runtime file. Also included is an example file.
var events = require('events');
var emitter = new events.EventEmitter();
function EventShim() {}
// String -> Boolean -> Boolean -> ()
EventShim.prototype.initEvent = function(t, bubbles, cancellable) {
this.name = t;
// Set by Elm.
this.value = undefined;
}
module.exports = {
// String -> Event
createEvent: function(eventtype) {
// eventtype should be "event", not enforced
return new EventShim();
},
// Event -> ()
dispatchEvent: function(e) {
emitter.emit(e.name, e.value)
},
// String -> (Event -> ()) -> ()
addEventListener: function(event, callback) {
var wrapped = function(value) {
callback({value: value});
}
emitter.on(event, wrapped);
}
}
var vm = require("vm");
var fs = require("fs");
var sandbox = { document: require('./document-wrapper.js') };
module.exports = function(runtimepath, modulepath) {
var runtime = fs.readFileSync(runtimepath);
var elmmodule = fs.readFileSync(modulepath);
vm.runInNewContext(runtime, sandbox, runtimepath);
vm.runInNewContext(elmmodule, sandbox, modulepath);
return sandbox.Elm;
}
var elmloader = require("./elmloader.js")
var Elm = elmloader('elm-runtime.js', 'build/Main.js')
var w = Elm.worker(Elm.Squarer)
var send = w.send('input')
console.log("Attempting to send")
w.recv('reply', function(e) {console.log("Got", e.value)});
for (var k = 0; k < 10; k++)
send(k);
module Squarer where
import JavaScript as JS
foreign import jsevent "input"
(JS.fromInt 0)
inputs: Signal JS.JSNumber
foreign export jsevent "reply"
outputs: Signal JS.JSNumber
numbers = JS.toInt <~ inputs
squares = (\n -> n^2) <~ numbers
outputs = JS.fromInt <~ squares
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment