简体   繁体   English

如何在Obj-C中使用回调定义Javascript函数?

[英]How do I define a Javascript function with a callback in Obj-C?

I'm using JavaScriptCore to evaluate some simple scripts in my app. 我正在使用JavaScriptCore评估我的应用程序中的一些简单脚本。 I'm creating a global object and defining some properties on it like so: 我正在创建一个全局对象,并在其上定义一些属性,如下所示:

JSContext *context = [[JSContext alloc] init];
JSValue *globalObject = [context globalObject];

[globalObject setValue:fields forProperty:@"fields"];
...

So then the script can access the values in fields and so on. 因此,脚本可以访问fields的值,依此类推。 I'd like scripts to be able to use a function called lookup , and I already have an Objective-C implementation for this function. 我希望脚本能够使用一个名为lookup的函数,并且我已经有此函数的Objective-C实现。

How do I add a property to the global object which is a function that calls back to my Objective-C method? 如何将属性添加到全局对象,该对象是一个回调我的Objective-C方法的函数? I see that there's a function called JSObjectMakeFunctionWithCallback , but that uses the low-level C constructs like JSObjectRef s and takes a C function, not an Objective-C block, so I can't make use of self inside the implementation. 我看到有一个名为JSObjectMakeFunctionWithCallback的函数,但是它使用了诸如JSObjectRef的低级C构造,并且使用了C函数,而不是Objective-C块,因此我无法在实现内部利用self

You can pass an Objective-C block to a JSContext and it will then behave as a function. 您可以将Objective-C块传递给JSContext,然后它将充当函数。 That way, your scripts can call back into your iOS code: 这样,您的脚本可以回调到您的iOS代码中:

context[@"factorial"] = ^(int x) {
    int factorial = 1;
    for (; x > 1; x--) {
        factorial *= x;
    }
    return factorial;
};
[context evaluateScript:@"var fiveFactorial = factorial(5);"];
JSValue *fiveFactorial = context[@"fiveFactorial"];
NSLog(@"5! = %@", fiveFactorial);

Source: Bignerdranch 资料来源: Bignerdranch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM