在Dart JS interop中提到"this"

uld*_*all 5 javascript dart dart-js-interop

我想在Dart中实现以下代码:

var HelloWorldScene = cc.Scene.extend({
    onEnter:function () {
        this._super();
    }
});
Run Code Online (Sandbox Code Playgroud)

我的Dart实现如下所示:

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

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

  void _onEnter() {
    context["this"].callMethod("_super");
  }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,运行代码时出现以下错误:

null对象没有方法'callMethod'

在以下行:

context ["this"].callMethod("_ super",[]);

context ["this"]似乎是null,所以我的问题是:如何从Dart引用"this"变量?

更新1:完整的示例代码可以在github上找到:https: //github.com/uldall/DartCocos2dTest

Ale*_*uin 1

this您可以使用JsFunction.withThis(f)捕获 Js 。通过该定义,将添加一个附加参数作为第一个参数。因此你的代码应该是:

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");
  }
}
Run Code Online (Sandbox Code Playgroud)