oke.
This commit is contained in:
+57
-33
@@ -2,42 +2,66 @@
|
||||
|
||||
@(require (for-label racket/base js-maker))
|
||||
|
||||
@title{js-maker use cases}
|
||||
@title{js-maker Use Cases}
|
||||
@author+email["Hans Dijkema" "hans@dijkewijk.nl"]
|
||||
|
||||
@section{Generating a small function}
|
||||
@defmodule[js-maker/demo/js-usecases]
|
||||
|
||||
@racketblock[
|
||||
(js (define (square x)
|
||||
(return (* x x))))
|
||||
]
|
||||
The demos in @filepath{demo/js-usecases.rkt} use only the public
|
||||
@racket[js] macro and the compact js-maker 3 form set. They are intentionally
|
||||
small: their purpose is to show the supported surface language, not to recreate
|
||||
the larger runtime-helper branch.
|
||||
|
||||
This produces a JavaScript function declaration. Racket identifiers are mapped
|
||||
to JavaScript-friendly names by replacing unsupported characters with
|
||||
underscores.
|
||||
@section{Random number}
|
||||
|
||||
@section{Generating a loop}
|
||||
|
||||
@racketblock[
|
||||
(js (define (sum-to n)
|
||||
(let loop ([i 0] [acc 0])
|
||||
(if (> i n)
|
||||
(return acc)
|
||||
(loop (+ i 1) (+ acc i))))))
|
||||
]
|
||||
|
||||
The named @racket[let] form is useful for simple loops while keeping ordinary
|
||||
Racket binding semantics for the initial values and loop updates.
|
||||
|
||||
@section{Generating DOM-style calls}
|
||||
|
||||
@racketblock[
|
||||
@codeblock{
|
||||
(js
|
||||
(define title (send document getElementById "title"))
|
||||
(set! (js-dot title innerHTML) "Hello")
|
||||
(send title addEventListener "click"
|
||||
(lambda (evt) (return #t))))
|
||||
]
|
||||
(define (randomBetween1And5)
|
||||
(return (+ (send Math floor (* (send Math random) 5)) 1))))
|
||||
}
|
||||
|
||||
This is string generation only. The generated JavaScript must still be run in a
|
||||
JavaScript environment that provides the referenced objects, such as
|
||||
@tt{document}.
|
||||
@section{Unique values}
|
||||
|
||||
@codeblock{
|
||||
(js
|
||||
(define (uniqueValues xs)
|
||||
(return (send Array from (new Set xs)))))
|
||||
}
|
||||
|
||||
@section{Indexed access}
|
||||
|
||||
@codeblock{
|
||||
(js
|
||||
(define (arrayAt xs i)
|
||||
(return (js-ref xs i))))
|
||||
}
|
||||
|
||||
@section{Named let loop}
|
||||
|
||||
@codeblock{
|
||||
(js
|
||||
(define (sumTo n)
|
||||
(let loop ([i 0] [acc 0])
|
||||
(if (> i n)
|
||||
(return acc)
|
||||
(loop (+ i 1) (+ acc i))))))
|
||||
}
|
||||
|
||||
@section{Function value}
|
||||
|
||||
@codeblock{
|
||||
(js
|
||||
(define (makeAdder x)
|
||||
(return (lambda (y)
|
||||
(return (+ x y))))))
|
||||
}
|
||||
|
||||
@section{DOM setter}
|
||||
|
||||
@codeblock{
|
||||
(js
|
||||
(define (setHtml id html)
|
||||
(let ([el (send document getElementById id)])
|
||||
(set! (js-dot el innerHTML) html)
|
||||
(return (js-dot el innerHTML)))))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user