【问题标题】:Referring to "this" in Dart JS interop在 Dart JS 互操作中引用“this”
【发布时间】:2015-07-21 17:01:04
【问题描述】:

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

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

我的 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");
  }
}

不幸的是,我在运行代码时收到以下错误:

空对象没有方法'callMethod'

在下面一行:

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

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

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

【问题讨论】:

  • 我猜你打错了:context[this].callMethod("_super");(不带引号)。
  • 不带引号的 'this' 将引用 HelloWorldScene Dart 类的实例。我希望在 Javascript VM 中的“this”变量上调用 _super()。
  • 你能发一个完整的例子吗?请问?
  • 我对 DartJS 不熟悉,但我建议在 context["this"].callMethod("_super"); 之前设置一个 debugger; 并查看 context 中的内容。
  • @Robert 我把完整的例子添加到了github。

标签: javascript dart dart-js-interop


【解决方案1】:

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

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");
  }
}

【讨论】:

  • 我现在收到以下错误:NoSuchMethodError: method not found: '_super'。看来这不是正确的“这个”我推迟了。
猜你喜欢
  • 2013-07-15
  • 1970-01-01
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-07
  • 1970-01-01
相关资源
最近更新 更多