Source

riak / apps / erlang_js / overview.edoc

Full commit
@author Kevin Smith (ksmith@basho.com)
@version 0.1
@title erlang_js: A Friendly Erlang to Javascript Binding

@doc
<p>
<h3>Description</h3>
erlang_js aims to be a simple and easy to use binding between Erlang and Javascript. erlang_js is packaged as an OTP application so it's easy to integrate.
</p>

<p>
<h3>Quick N' Dirty</h3>
<ol>
<li>Make sure the <code>sasl</code> application is running.</li>
<li>Start <code>erlang_js</code>.</li>
<li>Create a Javascript VM via <code>js_driver:new/0</code>.</li>
<li>Use the <code>js</code> module to execute Javascript.</li>
</ol>
</p>

<h3>Examples</h3>
<h4>Defining and calling a function</h4>
<pre>
{ok, Port} = js_driver:new().
ok = js:define(Port, &lt;&lt;"function my_add(x, y) { return x + y; }"&gt;&gt;).
js:call(Port, &lt;&lt;"my_add"&gt;&gt;, [100, 50]).
{ok, 150}
</pre>
<h4>Using a user-defined initializer</h4>
<pre>
InitFun = fun(Port) -> js:define(Port, &lt;&lt;"function my_square(x) { return x * x; }"&gt;&gt;), ok end.
{ok, Port} = js_driver:new(InitFun).
js:call(Port, &lt;&lt;"my_square"&gt;&gt;, [3]).
{ok,9}
</pre>
<h4>Using bindings</h4>
<pre>
InitFun = fun(Port) -> js:define(Port, &lt;&lt;"var my_constant = 100; function constant_mult(x) { return x * my_constant; };"&gt;&gt;), ok end.
{ok, Port} = js_driver:new(InitFun).
js:call(Port, &lt;&lt;"constant_mult"&gt;&gt;, [5]).
{ok, 500}
js:call(Port, &lt;&lt;"constant_mult"&gt;&gt;, [5], [{&lt;&lt;"my_constant"&gt;&gt;, 200}]).
{ok, 1000}
</pre>