Created
February 22, 2012 18:55
-
-
Save tristanz/1886636 to your computer and use it in GitHub Desktop.
Node module in header file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <node.h> | |
#include "complex.hpp" | |
using namespace v8; | |
void RegisterModule(Handle<Object> target) { | |
MyObject::Init(target); | |
} | |
NODE_MODULE(complex, RegisterModule); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef SENSECOMPLEX_HPP | |
#define SENSECOMPLEX_HPP | |
#include <node.h> | |
class MyObject : public node::ObjectWrap { | |
public: | |
static v8::Persistent<v8::FunctionTemplate> constructor; | |
static void Init(v8::Handle<v8::Object> target) { | |
v8::HandleScope scope; | |
v8::Local<v8::FunctionTemplate> tpl = v8::FunctionTemplate::New(New); | |
v8::Local<v8::String> name = v8::String::NewSymbol("MyObject"); | |
constructor = v8::Persistent<v8::FunctionTemplate>::New(tpl); | |
// ObjectWrap uses the first internal field to store the wrapped pointer. | |
constructor->InstanceTemplate()->SetInternalFieldCount(1); | |
constructor->SetClassName(name); | |
// Add all prototype methods, getters and setters here. | |
NODE_SET_PROTOTYPE_METHOD(constructor, "value", Value); | |
// This has to be last, otherwise the properties won't show up on the | |
// object in JavaScript. | |
target->Set(name, constructor->GetFunction()); | |
} | |
MyObject(int val) : node::ObjectWrap() { | |
value_ = val; | |
} | |
static v8::Handle<v8::Value> New(const v8::Arguments& args) { | |
v8::HandleScope scope; | |
if (!args.IsConstructCall()) { | |
return v8::ThrowException(v8::Exception::TypeError( | |
v8::String::New("Use the new operator to create instances of this object.")) | |
); | |
} | |
if (args.Length() < 1) { | |
return v8::ThrowException(v8::Exception::TypeError( | |
v8::String::New("First argument must be a number"))); | |
} | |
// Creates a new instance object of this type and wraps it. | |
MyObject* obj = new MyObject(args[0]->ToInteger()->Value()); | |
obj->Wrap(args.This()); | |
return args.This(); | |
} | |
static v8::Handle<v8::Value> Value(const v8::Arguments& args) { | |
v8::HandleScope scope; | |
// Retrieves the pointer to the wrapped object instance. | |
MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This()); | |
return scope.Close(v8::Integer::New(obj->value_)); | |
} | |
// Your own object variables here | |
int value_; | |
}; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment