constructor.h 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. // Copyright (c) 2018 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #ifndef ATOM_COMMON_API_CONSTRUCTOR_H_
  5. #define ATOM_COMMON_API_CONSTRUCTOR_H_
  6. #include "native_mate/constructor.h"
  7. namespace mate {
  8. // Create a FunctionTemplate that can be "new"ed in JavaScript.
  9. // It is user's responsibility to ensure this function is called for one type
  10. // only ONCE in the program's whole lifetime, otherwise we would have memory
  11. // leak.
  12. template <typename T, typename Sig>
  13. v8::Local<v8::Function> CreateConstructor(v8::Isolate* isolate,
  14. const base::Callback<Sig>& func) {
  15. #ifndef NDEBUG
  16. static bool called = false;
  17. CHECK(!called) << "CreateConstructor can only be called for one type once";
  18. called = true;
  19. #endif
  20. v8::Local<v8::FunctionTemplate> templ = CreateFunctionTemplate(
  21. isolate, base::Bind(&mate::internal::InvokeNew<Sig>, func));
  22. templ->InstanceTemplate()->SetInternalFieldCount(1);
  23. T::BuildPrototype(isolate, templ);
  24. return templ->GetFunction();
  25. }
  26. } // namespace mate
  27. #endif // ATOM_COMMON_API_CONSTRUCTOR_H_