allbto
allbto

Reputation: 169

Javascriptcore ios invoke class method

So I'm trying to understand how JavascriptCore works.

So first I tried calling single function, but now I'm trying to call a function inside a class.

My javascript code looks like this

var sayHelloAlfred = function()
{
    log("Hello Alfred");
}

var testClass = function()
{
    this.toto = function()
    {
        log("Toto in class");
    }
}

var testObject = {

    toto : function()
    {
        log("Toto in object");
    }

}

And my ViewController code :

- (void)viewDidLoad {
    [super viewDidLoad];

    _context = [[JSContext alloc] initWithVirtualMachine:[[JSVirtualMachine alloc] init]];

    _context[@"log"] = ^(NSString *text) {
        NSLog(@"%@", text);
    };

    NSString *scriptFilePath = [[NSBundle mainBundle] pathForResource:@"main" ofType:@"js"];
    NSString *scriptFileContents = [NSString stringWithContentsOfFile:scriptFilePath encoding:NSUTF8StringEncoding error:nil];
    [_context evaluateScript:scriptFileContents];
}

- (IBAction)doStuff:(id)sender
{
    [_context[@"sayHelloAlfred"] callWithArguments:@[]]; // Works
    [_context[@"testClass"] invokeMethod:@"toto" withArguments:@[]]; // Doesn't work
    [_context[@"testObject"] invokeMethod:@"toto" withArguments:@[]]; // Works
}

My problem is that it works perfectly with a single function and a function in an object but not with this in a function.

Do you know if this is the correct behavior of JavaScriptCore or if I'm doing something wrong ?

Thanks a lot in advance!

Upvotes: 1

Views: 484

Answers (1)

allbto
allbto

Reputation: 169

I realized that I was doing something wrong.

Since it's a class I first need to create an object before calling its methods.

That's how to do it :

JSValue* c = [_context[@"testClass"] constructWithArguments:@[]];
[c invokeMethod:@"toto" withArguments:@[]];

Upvotes: 1

Related Questions