Skip to content

Instantly share code, notes, and snippets.

@gabrielschulhof
Last active August 5, 2016 14:43
Show Gist options
  • Save gabrielschulhof/f1fbdeb251f1240316f967f93fa40c7a to your computer and use it in GitHub Desktop.
Save gabrielschulhof/f1fbdeb251f1240316f967f93fa40c7a to your computer and use it in GitHub Desktop.
template <class T> class JSHandle {
    static Nan::Persistent<v8::FunctionTemplate> &theTemplate() {
        static Nan::Persistent<v8::FunctionTemplate> returnValue;
        if (returnValue.IsEmpty()) {
            v8::Local<v8::FunctionTemplate> theTemplate =
                Nan::New<v8::FunctionTemplate>();
            theTemplate
                ->SetClassName(Nan::New(T::jsClassName()).ToLocalChecked());
            theTemplate->InstanceTemplate()->SetInternalFieldCount(1);
            Nan::Set(Nan::GetFunction(theTemplate).ToLocalChecked(),
                Nan::New("displayName").ToLocalChecked(),
                Nan::New(T::jsClassName()).ToLocalChecked());
            returnValue.Reset(theTemplate);
        }
        return returnValue;
    }
public:
    static v8::Local<v8::Object> New(void *data) {
        v8::Local<v8::Object> returnValue =
            Nan::GetFunction(Nan::New(theTemplate())).ToLocalChecked()
            ->NewInstance();
        Nan::SetInternalFieldPointer(returnValue, 0, data);
        return returnValue;
    }
    static void *Resolve(v8::Local<v8::Object> jsObject) {
        void *returnValue = 0;
        if (Nan::New(theTemplate())->HasInstance(jsObject)) {
            returnValue = Nan::GetInternalFieldPointer(jsObject, 0);
        }
        if (!returnValue) {
            Nan::ThrowTypeError((std::string("Object is not of type ") +
                T::jsClassName()).c_str());
        }
        return returnValue;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment