Skip to content

Commit

Permalink
Add ObjectWrap<T> subclass in instance data
Browse files Browse the repository at this point in the history
  • Loading branch information
Gabriel Schulhof committed Feb 3, 2020
1 parent 89aa6b6 commit 433a1a1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 7 deletions.
35 changes: 31 additions & 4 deletions test/addon_data.cc
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,36 @@

class Addon {
public:
Addon() {}
class VerboseIndicator : public Napi::ObjectWrap<VerboseIndicator> {
public:
VerboseIndicator(const Napi::CallbackInfo& info):
Napi::ObjectWrap<VerboseIndicator>(info) {
info.This().As<Napi::Object>()["verbose"] =
Napi::Boolean::New(info.Env(),
info.Env().GetInstanceData<Addon>()->verbose);
}

Napi::Value Getter(const Napi::CallbackInfo& info) {
return Napi::Boolean::New(info.Env(),
info.Env().GetInstanceData<Addon>()->verbose);
}

void Setter(const Napi::CallbackInfo& info, const Napi::Value& val) {
info.Env().GetInstanceData<Addon>()->verbose = val.As<Napi::Boolean>();
}

static Napi::FunctionReference Init(Napi::Env env) {
return Napi::Persistent(DefineClass(env, "VerboseIndicator", {
InstanceAccessor<
&VerboseIndicator::Getter,
&VerboseIndicator::Setter>("verbose")
}));
}
};

Addon(Napi::Env env): VerboseIndicator(VerboseIndicator::Init(env)) {}
bool verbose = false;
Napi::FunctionReference VerboseIndicator;
~Addon() {
if (verbose) {
fprintf(stderr, "addon_data: Addon::~Addon\n");
Expand All @@ -14,16 +42,15 @@ class Addon {
};

static Napi::Value Getter(const Napi::CallbackInfo& info) {
return Napi::Boolean::New(info.Env(),
info.Env().GetInstanceData<Addon>()->verbose);
return info.Env().GetInstanceData<Addon>()->VerboseIndicator.New({});
}

static void Setter(const Napi::CallbackInfo& info) {
info.Env().GetInstanceData<Addon>()->verbose = info[0].As<Napi::Boolean>();
}

Napi::Object InitAddonData(Napi::Env env) {
env.SetInstanceData(new Addon());
env.SetInstanceData(new Addon(env));
Napi::Object result = Napi::Object::New(env);

result.DefineProperties({
Expand Down
6 changes: 3 additions & 3 deletions test/addon_data.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ function test(bindingName) {
const binding = require(bindingName);

// Make sure it is possible to get/set instance data.
assert.strictEqual(binding.addon_data.verbose, false);
assert.strictEqual(binding.addon_data.verbose.verbose, false);
binding.addon_data.verbose = true;
assert.strictEqual(binding.addon_data.verbose, true);
assert.strictEqual(binding.addon_data.verbose.verbose, true);
binding.addon_data.verbose = false;
assert.strictEqual(binding.addon_data.verbose, false);
assert.strictEqual(binding.addon_data.verbose.verbose, false);

// Make sure the instance data finalizer is called at process exit.
const child = spawn(process.execPath, [
Expand Down

0 comments on commit 433a1a1

Please sign in to comment.