コード例 #1
0
ファイル: IGUIObject.cpp プロジェクト: Rektosauros/0ad
void IGUIObject::RegisterScriptHandler(const CStr& Action, const CStr& Code, CGUI* pGUI)
{
	if(!GetGUI())
		throw PSERROR_GUI_OperationNeedsGUIObject();

	JSContext* cx = pGUI->GetScriptInterface()->GetContext();
	JSAutoRequest rq(cx);
	JS::RootedValue globalVal(cx, pGUI->GetGlobalObject());
	JS::RootedObject globalObj(cx, &globalVal.toObject());

	const int paramCount = 1;
	const char* paramNames[paramCount] = { "mouse" };

	// Location to report errors from
	CStr CodeName = GetName()+" "+Action;

	// Generate a unique name
	static int x = 0;
	char buf[64];
	sprintf_s(buf, ARRAY_SIZE(buf), "__eventhandler%d (%s)", x++, Action.c_str());

	JS::CompileOptions options(cx);
	options.setFileAndLine(CodeName.c_str(), 0);
	options.setCompileAndGo(true);

	JS::RootedFunction func(cx, JS_CompileFunction(cx, globalObj,
		buf, paramCount, paramNames, Code.c_str(), Code.length(), options));

	if (!func)
		return; // JS will report an error message

	JS::RootedObject funcObj(cx, JS_GetFunctionObject(func));
	SetScriptHandler(Action, funcObj);
}
コード例 #2
0
ファイル: global.cpp プロジェクト: dumganhar/libjsapi
bool rs::jsapi::Global::DefineFunction(Context& cx, const char* name, FunctionCallback callback, unsigned attrs) {
    JSAutoRequest ar(cx);
    JS::RootedFunction func(cx, JS_NewFunction(cx, CallFunction, 0, 0, JS::NullPtr(), name));
    JS::RootedObject funcObj(cx, JS_GetFunctionObject(func));
    
    JS::RootedObject privateFuncObj(cx, JS_NewObject(cx, &privateFunctionStateClass_, JS::NullPtr()));
    JS_SetPrivate(privateFuncObj, new GlobalFunctionState(callback));
    JS_DefineProperty(cx, funcObj, privateFunctionStatePropertyName_, privateFuncObj, 0, nullptr, nullptr);

    return JS_DefineProperty(cx, cx.getGlobal(), name, funcObj, attrs, nullptr, nullptr);
}