I've been trying to create methods dynamically from strings using Dart to no avail. String example: "(String str) => return str.length;". The idea is to allow users to create their own functions to apply to a given string. The only thing I've found is NoSuchMethod which does not seem to apply to my case. I tried using new Function in JavaScript but when passing the function to Dart and executing it, I get the following error: Uncaught TypeError: J.$index$asx(...).call$0 is not a function.
Code examples:
Dart:
// PHP code
$files = scandir('stathtml/');
foreach ($files as $file) {
$arr1 = substr($files, -5);
$arr1 = substr($arr1, 4);
$arr2 = substr($files, 3);
echo $file . "<br>";
echo "section ".$arr1 . "<br>";
echo "chapter".$arr2 . "<br>";
}
JS:
context["UpdateNames"] =
(JsObject pTag)
{
print(pTag["function"]("text"));
};
EDIT:
Solution: Create an object in JavaScript such as this:
function execute ()
{
var func = {"function": new Function("str", "return str.length;")};
UpdateNames(func);
}
Then create the object in Dart:
this.fun = function (name)
{
var text = "var funs = " + document.getElementById("personalFun").value;
eval(text);
return funs(name);
};
Finally call the method to dynamically create the function:
caller = new JsObject(context['Point'], []);
答案 0 :(得分:3)
我不确定完全理解你想要达到的目标,所以我会努力提供最好的答案
在这种情况下,它完全可以,但你需要使用一些镜像所以要小心,如果你想将它用于网络
这是一个实现示例:
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 :(得分: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]);