Advertisement
Guest User

Untitled

a guest
Jul 29th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. /*
  2. Coded by Darko Lukic <lukicdarkoo@gmail.com>
  3. Node.js and C++ bindings with events (EventEmitter)
  4. */
  5.  
  6. #include <nan.h>
  7. #include <iostream>
  8.  
  9. using v8::Local;
  10. using v8::FunctionTemplate;
  11. using v8::Object;
  12. using v8::Value;
  13. using v8::Handle;
  14. using v8::Isolate;
  15. using v8::Exception;
  16. using v8::Persistent;
  17. using v8::Context;
  18. using namespace std;
  19.  
  20. class Robot : public Nan::ObjectWrap {
  21. public:
  22. static void Init(Local<Object> exports) {
  23. Nan::HandleScope scope;
  24.  
  25. Local<FunctionTemplate> tmpl = Nan::New<FunctionTemplate>(New);
  26. tmpl->InstanceTemplate()->SetInternalFieldCount(1);
  27.  
  28. Nan::SetPrototypeMethod(tmpl, "getX", getX);
  29. Nan::SetPrototypeMethod(tmpl, "setX", setX);
  30.  
  31. exports->Set(Nan::New("Robot").ToLocalChecked(), tmpl->GetFunction());
  32. }
  33.  
  34. static void New(const Nan::FunctionCallbackInfo<Value>& args) {
  35. Nan::HandleScope scope;
  36.  
  37. Robot *robot = new Robot();
  38. robot->Wrap(args.This());
  39.  
  40. args.GetReturnValue().Set(args.This());
  41. }
  42.  
  43. Robot() : x(0) {}
  44.  
  45. Persistent<Object> obj;
  46.  
  47. private:
  48.  
  49.  
  50. static void getX(const Nan::FunctionCallbackInfo<Value>& args) {
  51. Nan::HandleScope scope;
  52.  
  53. Robot *robot = ObjectWrap::Unwrap<Robot>(args.Holder());
  54.  
  55. args.GetReturnValue().Set(robot->x++);
  56. }
  57.  
  58. static void setX(const Nan::FunctionCallbackInfo<Value>& args) {
  59. Nan::HandleScope scope;
  60.  
  61. Robot *robot = ObjectWrap::Unwrap<Robot>(args.Holder());
  62.  
  63. // Set x
  64. if (args.Length() != 1 || args[0]->IsInt32() == false) {
  65. args.GetIsolate()->ThrowException(Exception::TypeError(
  66. Nan::New("Function requires one argument").ToLocalChecked()
  67. ));
  68. return;
  69. }
  70. else {
  71. robot->x = args[0]->Int32Value();
  72. }
  73.  
  74. (robot->obj).Reset(args.GetIsolate(), args.Holder());
  75.  
  76.  
  77. // Fire event
  78. Handle<Value> argv[] = {
  79. Nan::New("positionChanged").ToLocalChecked(),
  80. Nan::New(robot->x)
  81. };
  82.  
  83. Nan::MakeCallback(Nan::New(robot->obj), "emit", 2, argv);
  84. }
  85.  
  86. int x;
  87. };
  88.  
  89. NODE_MODULE(Robot, Robot::Init)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement