From d4a8bcaa5e26ebad3b391199dcb8d4962bb00ef4 Mon Sep 17 00:00:00 2001 From: Travis DePrato Date: Fri, 20 Dec 2019 17:53:21 -0800 Subject: [PATCH] Update README for JSExpr v1.0. --- README.md | 147 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 101 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index e304d4e..1430d5d 100644 --- a/README.md +++ b/README.md @@ -4,83 +4,138 @@ |-------|----------| | [![Build Status](https://travis-ci.org/JuliaGizmos/JSExpr.jl.svg?branch=master)](https://travis-ci.org/JuliaGizmos/JSExpr.jl) | [![codecov](https://codecov.io/gh/JuliaGizmos/JSExpr.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/JuliaGizmos/JSExpr.jl) -This package provides the `@js` macro which translates a Julia expression to JavaScript. +This package provides two macros that are used to write JavaScript code inside +of Julia programs. +* The `@js` macro translates Julia syntax to the equivalent JavaScript +* The `@js"..."` macro is used to write code using string literals with _smart_ + interpolation of values from Julia -## Example +## Examples ```julia julia> using JSExpr julia> @js document.querySelector("#root") -WebIO.JSString("document.querySelector(\"#root\")") +JSString("document.querySelector(\"#root\")") -julia> @js (a,b) -> a+b -WebIO.JSString("(function (a,b){return (a+b)})") -``` +julia> @js (a, b) -> a + b +JSString("(a, b) => { return a + b; }") -The `JSString` object wraps a Julia string. You can access the plain string from the `.s` field. +julia> config = Dict("foo" => "bar"); +julia> js"initializeProgram($config);" +JSString("initializeProgram({\"foo\":\"bar\"});") +``` ## Interpolation -You can interpolate Julia objects or `JSString` expressions (i.e. result of `@js` macro invocations) in a `@js` macrocall. +You can interpolate Julia objects or `JSString`'s (e.g. from other `@js` or + `js"..."` invocations) as well. ```julia -julia> foo = 42 -42 - +julia> foo = 42; julia> callback = @js a -> a + $foo -WebIO.JSString("(function (a){return (a+42)})") +JSString("(a) => { return a + 42; }") julia> f = @js array -> array.map($callback) -WebIO.JSString("(function (array){return array.map((function (a){return (a+42)}))})") +JSString("(array) => { return array.map((a) => { return a + 42; }); }") ``` -Converting a `JSString` or an object containing it to JSON serializes JSString as a string. +#### Custom Interpolation +By default, values are serialized using the `JSON` package. +This makes sense for `Dict`s, `Array`s, and most other "primitive" types. -```julia -julia> JSON.print(Dict("foo" => "bar", "bar"=>f)) -{"bar":"(function (array){return array.map((function (a){return (a+42)}))})","foo":"bar"} -``` -This is not ideal when you want to use the serialized output as JavaScript, for example in a `