Add EmitEvent function to replace node::MakeCallback

This commit is contained in:
Cheng Zhao 2015-06-23 19:46:37 +08:00
parent 197a9b4165
commit 78459b913b
5 changed files with 87 additions and 26 deletions

View file

@ -0,0 +1,33 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/event_emitter_caller.h"
namespace mate {
namespace internal {
v8::Local<v8::Value> CallEmitWithArgs(v8::Isolate* isolate,
v8::Local<v8::Object> obj,
ValueVector* args) {
v8::Local<v8::String> emit_name = StringToSymbol(isolate, "emit");
v8::Local<v8::Value> emit = obj->Get(emit_name);
if (emit.IsEmpty() || !emit->IsFunction()) {
isolate->ThrowException(v8::Exception::TypeError(
StringToV8(isolate, "\"emit\" is not a function")));
return v8::Undefined(isolate);
}
v8::MaybeLocal<v8::Value> result = emit.As<v8::Function>()->Call(
isolate->GetCurrentContext(), obj, args->size(), &args->front());
if (result.IsEmpty()) {
return v8::Undefined(isolate);
}
return result.ToLocalChecked();
}
} // namespace internal
} // namespace mate

View file

@ -0,0 +1,40 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_COMMON_EVENT_EMITTER_CALLER_H_
#define ATOM_COMMON_EVENT_EMITTER_CALLER_H_
#include <vector>
#include "native_mate/converter.h"
namespace mate {
namespace internal {
using ValueVector = std::vector<v8::Local<v8::Value>>;
v8::Local<v8::Value> CallEmitWithArgs(v8::Isolate* isolate,
v8::Local<v8::Object> obj,
ValueVector* args);
} // namespace internal
// obj.emit(name, args...);
// The caller is responsible of allocating a HandleScope.
template<typename... Args>
v8::Local<v8::Value> EmitEvent(v8::Isolate* isolate,
v8::Local<v8::Object> obj,
const base::StringPiece& name,
const Args&... args) {
internal::ValueVector converted_args = {
ConvertToV8(isolate, name),
ConvertToV8(isolate, args)...,
};
return internal::CallEmitWithArgs(isolate, obj, &converted_args);
}
} // namespace mate
#endif // ATOM_COMMON_EVENT_EMITTER_CALLER_H_