Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referring to "this" in Dart JS interop

I want to implement the following code in Dart:

var HelloWorldScene = cc.Scene.extend({
    onEnter:function () {
        this._super();
    }
});

My Dart implementation looks like this:

class HelloWorldScene {
  HelloWorldScene() {
    var sceneCollectionJS = new JsObject.jsify({ "onEnter": _onEnter});

    context["HelloWorldScene"] = context["cc"]["Scene"].callMethod("extend", [sceneCollectionJS]);
  }

  void _onEnter() {
    context["this"].callMethod("_super");
  }
}

Unfortunately I get the following error when running the code:

The null object does not have a method 'callMethod'

on the following line:

context["this"].callMethod("_super", []);

context["this"] seems to be null, so my question is: How do I refer to the "this" variable from Dart?

UPDATE 1: The full example code can be found on github: https://github.com/uldall/DartCocos2dTest

like image 472
uldall Avatar asked Nov 10 '22 13:11

uldall


1 Answers

You can capture the Js this with JsFunction.withThis(f). With that definition an additionnal argument will be added as first argument. Thus your code should be :

import 'dart:js';

class HelloWorldScene {
  HelloWorldScene() {
    var sceneCollectionJS =
        new JsObject.jsify({"onEnter": new JsFunction.withThis(_onEnter)});

    context["HelloWorldScene"] =
        context["cc"]["Scene"].callMethod("extend", [sceneCollectionJS]);
  }

  void _onEnter(jsThis) {
    jsThis.callMethod("_super");
  }
}
like image 55
Alexandre Ardhuin Avatar answered Nov 14 '22 22:11

Alexandre Ardhuin