I am trying to do some experiments with the JS backend. I would have thought that echo would be mapped to console.log, but unfortunately it is mapped to some document manipulation, which only works inside a browser.
I could not find console inside the dom module, so I guess my question is twofold. First, how does one import foreign js functions? And second, wouldn't it be better to have echo bound to console.log by default. It is not often the case that one wants to append a div to the body directly.
type Console {.importc.} = object of RootObj
log: proc(a: string) {.nimcall.}
var console {.importc, nodecl.}: Console
The only problem is that log requires a concrete type, and I cannot find a way to express the fact that console.log in js eats everything. I tried making the procedure generic or using any as a type, but the compiler rejects it.
Also, making log a non member proc or a method makes it compile into a function instead of a method on console, and this fails
Great! :-)
Still curious, though: if I had to bind console.log myself, how would I express the fact that it is polymorphic? (@novist: I am not talking about the variable arity here, just the fact that every type is loggable, while I am forced to mention a concrete one, such as string)
This is not true. Javascript consoles are able to show, for instance, navigable objects, so we do not want to convert everything to string before passing it to console.log.
More in general, the problem is: if I have a javascript method that, being untyped, accepts any as input, how do I wrap it in javascript? The problem arises from the fact that:
I may have missed something here, but it seems that this requires a {.magic.} pragma and compiler support
Doesn't seem hard to do, idea:
type
JsObj = ref object
proc toJs[T](x: T): JsObj =
asm """
return `x`;
"""
proc takesAnything(x: varargs[toJS, JsObj]) {.importc, nodecl.}
takesAnything("foobar", 7, 88, 9.0, false)