Skip to content
Craig Minihan edited this page Apr 22, 2015 · 25 revisions

rs::jsapi::Object is an implementation of a static object. Object should be used when the fields are known in advance. In this example the object has one field: 'the_answer'.

The getter lambda takes the parameters: const char* name, Value& value where name is the name of the field being referenced from JavaScript and the value parameter takes the return value (the field value). In this example we only have one field so we always return 42.

#include <iostream>
#include "libjsapi.h"

int main() {
    rs::jsapi::Runtime rt;

    // create an object with a single field 'the_answer' with a getter
    // callback which always returns 42
    rs::jsapi::Value obj(rt);
    rs::jsapi::Object::Create(rt, { "the_answer" },
        [](const char* name, rs::jsapi::Value& value) { value.set(42); return true; },
        nullptr,
        {},
        nullptr,
        obj);

    // create a function which returns the value of the field 'the_answer'
    // on the passed object
    rt.Evaluate("var myfunc=function(o){return o.the_answer;};");

    rs::jsapi::FunctionArguments args(rt);
    args.Append(obj);

    // invoke the function and get the result
    rs::jsapi::Value result(rt);
    rt.Call("myfunc", args, result);

    // output the result to the console
    std::cout << result << std::endl;

    return 0;
}
Clone this wiki locally