Skip to content
Peter Reijnders edited this page Jan 26, 2017 · 1 revision

Attribute name: Exposed

  • Name: exposed

  • Usage on 'Interface'

  • Since: draft

  • Allowed values: one of: ['class', 'module', '/a-z/+', 'embed']

  • Rationale: No all classes need to be available for the usercode:

    • build-in: several do need to be build-in (e.g. HTTP),
    • embed: several are loadable (e.g. DB)
    • module: several are modules (e.g. NativeRedis)
    • once: several will be automatically instantiated in the global namespace.

    To structure this and ease the creation of templates this attribute is helpful.

  • Reference 'Console'

Example 'Console' (once)

Sometimes it is needed to instantiate a class once-and-only-only in the global namespace. Is this case the global variable name can be provided as the value of the 'exposed' attribute.

IDL

[ exposed=console] interface Console {
	            static void log( optional DOMString text );
	[Alias=log] static void warn (optional DOMString text );
};

c++

void JSConsole::RegisterObject(JSContext *cx)
{
    JSConsole::ExposeClass(cx, "Console");
    JSConsole::CreateUniqueInstance(cx, new JSConsole(), "console");
}

Javascript

console.log(type console);

Example 'DB' (embed)

IDL

[ exposed=embed] interface DB {
};

C++

static JSObject *registerCallback(JSContext *cx)
{
    JS::RootedObject obj(cx, JS_NewPlainObject(cx));
    JSDB::ExposeClass<1>(cx, "DB", 0, JSDB::kEmpty_ExposeFlag, obj);
    JS::RootedValue val(cx);
    if (!JS_GetProperty(cx, obj, "DB", &val)) {
        return nullptr;
    }
    JS::RootedObject ret(cx, val.toObjectOrNull());

    return ret;
}

void JSDB::RegisterObject(JSContext *cx)
{
    JSModules::RegisterEmbedded("DB", registerCallback);
}

Javascript

var DB = require("DB");
var db = new DB("mydb_base");
console.log(type db);

Example 'OS' (module)

IDL

[ exposed=module ] interface OS {
};

c++

void JSOS::RegisterObject(JSContext *cx)
{
    JSModules::RegisterEmbedded("OS", JSOS::RegisterModule);
}

JSObject *JSOS::RegisterModule(JSContext *cx)
{
    JS::RootedObject exports(cx, JSOS::ExposeObject(cx, "OS"));

    return exports;
}

Javascript

var OS = require("OS");
console.log(OS.language);

Example 'Socket' (class)

IDL

[ exposed=class ] interface Socket {
};

c++

void JSSocket::RegisterObject(JSContext *cx)
{
    JSSocket::ExposeClass<2>(cx, "Socket");
    JSSocketClientConnection::ExposeClass(cx, "SocketClientConnection");

Javascript

var socket = new Socket("0.0.0.0", 8003).listen();
socket.onaccept = function(clientSocket) {
    clientSocket.write("hello !\\n");
}

Example SocketClient (not set)

[ ] interface SocketClient {
};
//the SocketClient class is not exposed to the usercode
var socket = new Socket("0.0.0.0", 8003).listen();
socket.onaccept = function(clientSocket) {
    console.log(type clientSocket);
    clientSocket.write("hello !\\n");
});