static void Init(Handle<Object> target) {
v8::HandleScope scope; // used by v8 for garbage collection
// Our constructor
v8::Local<FunctionTemplate> local_function_template = v8::FunctionTemplate::New(New);
Gtknotify::persistent_function_template = v8::Persistent<FunctionTemplate>::New(local_function_template);
Gtknotify::persistent_function_template->InstanceTemplate()->SetInternalFieldCount(1); // 1 since this is a constructor function
Gtknotify::persistent_function_template->SetClassName(v8::String::NewSymbol("Notification"));
// Our getters and setters
Gtknotify::persistent_function_template->InstanceTemplate()->SetAccessor(String::New("title"), GetTitle, SetTitle);
Gtknotify::persistent_function_template->InstanceTemplate()->SetAccessor(String::New("icon"), GetIcon, SetIcon);
// Our methods
NODE_SET_PROTOTYPE_METHOD(Gtknotify::persistent_function_template, "send", Send);
// Binding our constructor function to the target variable
target->Set(String::NewSymbol("notification"), Gtknotify::persistent_function_template->GetFunction());
}
剩下要做的就是编写我们在Init方法中用的C++方法:New,GetTitle,SetTitle,GetIcon,SetIcon,Send
构造器方法: New()
New() 方法创建了我们自定义类的新实例(一个 Gtknotify 对象),并设置一些初始值,然后返回该对象的 JavaScript 处理。这是 JavaScript 使用 new 操作符调用构造函数的期望行为。
std::string title;
std::string icon;
// new notification()
static Handle<Value> New(const Arguments& args) {
HandleScope scope;
Gtknotify* gtknotify_instance = new Gtknotify();
// Set some default values
gtknotify_instance->title = "Node.js";
gtknotify_instance->icon = "terminal";
// Wrap our C++ object as a Javascript object
gtknotify_instance->Wrap(args.This());
return args.This();
}
getters 和 setters: GetTitle(), SetTitle(), GetIcon(), SetIcon()
下面主要是一些样板代码,可以归结为 C++ 和 JavaScript (v8) 之间的值转换。
// this.title
static v8::Handle<Value> GetTitle(v8::Local<v8::String> property, const v8::AccessorInfo& info) {
// Extract the C++ request object from the JavaScript wrapper.
Gtknotify* gtknotify_instance = node::ObjectWrap::Unwrap<Gtknotify>(info.Holder());
return v8::String::New(gtknotify_instance->title.c_str());
}
// this.title=
static void SetTitle(Local<String> property, Local<Value> value, const AccessorInfo& info) {
Gtknotify* gtknotify_instance = node::ObjectWrap::Unwrap<Gtknotify>(info.Holder());
v8::String::Utf8Value v8str(value);
gtknotify_instance->title = *v8str;









