I would like to use the flot.js 2D plot library from elm. I first thought I'd write a native wrapper for it but it seems to be discouraged. I therefore want to try to use ports to send the values to plot to JavaScript (ie the call to flot.js would be made on the JavaScript side). Is this possible?
2 Answers
Yes, you can use ports to send data from Elm to plot into a Flot graph. Here's a rewrite of the Basic Flot Example using Elm as the data source.
port flotExample1 : List (List (Maybe (List Float)))
port flotExample1 =
let
halfStepsTo14 =
List.map (\x -> x / 2) [0..28]
d1 =
List.map (\x -> Just [x, sin x]) halfStepsTo14
d2 =
List.map Just [[0, 3], [4, 8], [8, 5], [9, 13]]
d3 =
[Just [0, 12], Just [7, 12], Nothing, Just [7, 2.5], Just [12, 2.5]]
in
[ d1, d2, d3 ]
Elm will do the conversion of basic Elm datatypes in ports to Javascript types on the other side. The Maybe
in the function signature above is to account for the fact that nulls can be used to separate line segments in Flot (see example d3
)
<script>
var app = Elm.worker(Elm.Main);
$(function() {
$.plot("#placeholder", app.ports.flotExample1);
});
</script>
You can make more complex examples like accessing a server URL from Elm or tying into other Signals like Time or mouse movements (in which case your port signature will be a Signal (List (List (Maybe (List Float))))
), but it will still all revolve around ports.

- 36,115
- 4
- 89
- 97
-
I chose your answer because it looks more idiomatic. But what's stopping us from creating an 'eval' port of the Signal String type & running eval on it inside the script tag? I'm pretty sure Evan Czaplicki would be horrified... – Deimos Jan 06 '16 at 20:30
-
Sure, you *could* make an `eval()` port subscriber and concatenate JavaScript strings in elm, but it kinda defeats the purpose of using elm in the first place. The boundary layer of ports offers a clean separation of anything-goes JavaScript and type-safe, pure elm code. I think you'd be shooting yourself in the foot to try and blur that line by generating JavaScript strings for evaluation. – Chad Gilbert Jan 06 '16 at 20:58
-
That's what I thought. I was thinking of doing this as a quick and dirty hack to use an existing JavaScript library such as flot.js because native modules look like a recipe to shoot yourself in the foot anyway... – Deimos Jan 07 '16 at 05:16
I don't see why not. You could build a data structure in elm containing your instructions for flot.js (or in your case maybe just an array of points), and pass that set of instructions to javascript through a port. Then in javascript process the instructions and make calls to flot.js.

- 1,064
- 8
- 13