tags:

views:

23

answers:

0

This is basically the sample code from the 'Getting started' section of the documentation in which I stubbed out an ObjectTemplate provided with a NamedPropertyHandler.

The JSON.stringify is just there to trigger an enumeration over the object's keys.

The code can be compiled and run as is.

#include <v8.h>

using namespace v8;

Handle<Value> 
Getter(Local<String> property, const AccessorInfo& info ) {
    return String::New("42!");
}

Handle<Boolean> 
Deleter(Local<String> property, const AccessorInfo& info ) {
    return False();
}

Handle<Value> 
Setter(Local<String> property, Local<Value> value,
             const AccessorInfo& info ) {
    return Null();
}

Handle<Array> 
Enumerator(const AccessorInfo& info) {
    Handle<Array> result = Array::New();
    result->Set(0, String::New("universalAnswer"));
    return result;
}

Handle<Integer> 
Query(Local<String> property, const AccessorInfo& info) {
    return Integer::New(DontDelete);
}

int main(int argc, char* argv[]) {
  HandleScope handle_scope;
  Persistent<Context> context = Context::New();
  Context::Scope context_scope(context);

  Handle<ObjectTemplate> tmpl = ObjectTemplate::New();
  tmpl->SetNamedPropertyHandler(Getter, Setter,Query, Deleter,Enumerator);
  context->Global()->Set(String::New("test"), tmpl->NewInstance() );

  Handle<String> source = String::New("JSON.stringify(test)");

  Handle<Script> script = Script::Compile(source);
  Handle<Value> result = script->Run();
  context.Dispose();
  String::AsciiValue ascii(result);
  printf("%s\n", *ascii);
  return 0;
}