首页 文章

Dart:从字符串创建方法

提问于
浏览
1

我发现NoSuchMethod似乎不适用于我的情况 . 我尝试在JavaScript中使用新函数但是当将函数传递给Dart并执行它时,我收到以下错误: Uncaught TypeError: J.$index$asx(...).call$0 is not a function .

代码示例:

镖:

context["UpdateNames"] =

(JsObject pTag)
{
    print(pTag["function"]("text"));
};

JS:

function execute ()
{
    var func = {"function": new Function("str", "return str.length;")};
    UpdateNames(func);
}

EDIT:

解决方案:在JavaScript中创建一个对象,例如:

this.fun = function (name)
  {
    var text = "var funs = " + document.getElementById("personalFun").value;
    eval(text);
    return funs(name);
  };

然后在Dart中创建对象:

caller = new JsObject(context['Point'], []);

最后调用方法动态创建函数:

caller.callMethod('fun', [text]);

2 回答

  • 2

    我不确定完全理解你想要达到的目标,所以我会努力提供最好的答案

    您希望将方法动态添加到具有特定字符串标识符的类

    在这种情况下,它是完全可能的,但你需要 use some mirror 所以 be careful if you want to use this for the web

    这里有一个实现示例:

    import "dart:mirrors";
    
    class Test {
      Map<String, dynamic> _methods = {};
    
      void addMethod(String name, var cb) {
        _methods[name] = cb;
      }
    
      void noSuchMethod(Invocation inv) {
        if (inv.isMethod) {
          Function.apply(_methods[MirrorSystem.getName(inv.memberName)],     inv.positionalArguments);
        }
      }
    }
    
    void testFunction() {
      for (int i = 0; i < 5; i++) {
        print('hello ${i + 1}');
      }
    }
    
    void testFunctionWithParam(var n) {
      for (int i = 0; i < 5; i++) {
        print('hello ${i + n}');
      }
    }
    
    void main() {
      var t = new Test();
    
      t.addMethod("printHello", testFunction);
      t.addMethod("printHelloPlusN", testFunctionWithParam);
      t.printHello();
      t.printHelloPlusN(42);
    }
    

    您想在字符串中“执行”代码

    对不起但是不可能 . 这是一个很大的要求,但是飞镖队没有计划,因为这将涉及许多变化和传统 .

    也许有可能通过创建dart文件并使用isolate来运行它 .

  • 1

    解决方案:在JavaScript中创建一个对象,例如:

    var FunctionObject = function() {
      this.fun = function (name)
      {
        var text = "var funs = " + document.getElementById("personalFun").value;
        eval(text);
        return funs(name);
      };
    };
    

    然后在Dart中创建对象:

    caller = new JsObject(context['FunctionObject'], []);
    

    最后调用方法动态创建函数:

    caller.callMethod('fun', [text]);
    

相关问题