我有一个全局事件管理器,允许您使用 lambdas 监听string
事件名称。
// somewhere in the ModuleScript class
Event->Listen("WindowResize", [=]{
// ...
});
现在,我也想从 JavaScript 注册事件。因此,我写了这个回调。
v8::Handle<v8::Value> ModuleScript::jsOn(const v8::Arguments& args)
{
// get pointer to class since we're in a static method
ModuleScript *module = (ModuleScript*)HelperScript::Unwrap(args.Data());
// get event name we want to register to from arguments
if(args.Length() < 1 || !args[0]->IsString())
return v8::Undefined();
string name = *v8::String::Utf8Value(args[0]);
// get callback function from arguments
if(args.Length() < 2 || !args[1]->IsFunction())
return v8::Undefined();
v8::Handle<v8::Function> callback =
v8::Local<v8::Function>::Cast(args[1]->ToObject());
// register event on global event manager
module->Event->Listen(name, [=]{
// create persistent handle so that function stays valid
// maybe this doesn't work, I don't know
v8::Persistent<v8::Function> function =
v8::Persistent<v8::Function>::New(args.GetIsolate(), callback);
// execute callback function
// causes the access violation
function->Call(function, 0, NULL);
});
return v8::Undefined();
}
触发事件时,应用程序会因访问冲突而崩溃。我的想法是函数对象此时不再有效,或者是 JavaScript 范围问题。但我想不通。
什么导致访问冲突以及如何克服它?