Skip to content

Instantly share code, notes, and snippets.

@yocontra
Created April 24, 2012 08:12
Show Gist options
  • Save yocontra/2477770 to your computer and use it in GitHub Desktop.
Save yocontra/2477770 to your computer and use it in GitHub Desktop.
Emitting events from a native node/v8 module
/*
You need to mix EventEmitter into MyObject from the JS end before you can emit/listen for events
*/
bool MyObject::Emit(const char *event, int argCount, Handle<Value> emitArgs[])
{
HandleScope scope;
//Format arguments to pass to v8::Function
int nArgCount = argCount + 1;
Handle<Value> *nEmitArgs = new Handle<Value>[nArgCount];
//Integrity checks
if (nEmitArgs == NULL)
{
return false;
}
if (this->handle_.IsEmpty())
{
return false;
}
//nEmitArgs = ['coolEvent', other args...]
nEmitArgs[0] = String::New(event);
if (emitArgs != NULL)
{
for (int i = 0; i < argCount; i++)
{
nEmitArgs[i + 1] = emitArgs[i];
}
}
//Emit event
Local<Value> emit_v = this->handle_->Get(NODE_SYMBOL("emit"));
if (!emit_v->IsFunction())
{
return false;
}
Local<Function> emitf = Local<Function>::Cast(emit_v);
TryCatch try_catch;
emitf->Call(this->handle_, nArgCount, nEmitArgs);
//Cleanup
delete [] nEmitArgs;
if (try_catch.HasCaught())
{
FatalException(try_catch);
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment