Skip to content

How an impure Elm Native module may look

Noah edited this page May 25, 2017 · 1 revision

Pre-warning

Write as much as your code as possible in Elm. Elm is safe. Javascript, and therefore Native, is not. Introducing Native code can make your application much harder to debug and rely on. One of the things we love about Elm is that if it compiles, we're pretty sure we won't get runtime errors. Native modules can and will introduce runtime errors.

Make sure to read this first.

See this for updated info for 0.18 onwards.

Boilerplate

Follow the example here

Getting started

Let's make a Native module that allows you to get a random number without needing a seed.

To begin, let's define our Elm code. Below is the file src/MyModule.elm

module MyModule (getRandom) where

-- this will be our function which returns a random number
getRandom : Task x Float
getRandom = Native.MyModule.getRandom

Now, let's actually implement the Native side -

var getRandom = function(Task){
  return function() {
    return Task.asyncFunction(function(callback){
      return callback(Task.succeed(Math.getRandom()));
    });
  };
};

var make = function make(elm) {
    elm.Native = elm.Native || {};
    elm.Native.MyModule = elm.Native.MyModule || {};

    if (elm.Native.MyModule.values) return elm.Native.MyModule.values;

    var Task = Elm.Native.Task.make(elm);

    return {
        'getRandom': getRandom(Task)
    };
};

Elm.Native.MyModule = {};
Elm.Native.MyModule.make = make;
Clone this wiki locally