简体   繁体   English

从Dart创建js对象

[英]Create js Objects from Dart

I have js code that needs to be translatable to Dart: 我有需要翻译为Dart的js代码:

(function() {
    var s, e;
    s = document.createElement("script");
    s.src = “//someurl.com/somefile.js";
    s.async = true;
    e = document.getElementsByTagName("head")[0];
    e.insertBefore(s, e.firstChild);
    this.OBJECT = this.OBJECT || {};
    this.OBJECT.array = this.OBJECT.somearray || [];
})();

OBJECT.somearray.push({
    val1 : “foo",
    val2 : “bar"
});

Basic part to embed script into head I did like this: 我将脚本嵌入到头部的基本部分是这样的:

ScriptElement scr = new ScriptElement()
  ..src = "//someurl.com/somefile.js";
  ..async = true;
querySelector('head').append(scr);

But I don't know how to correctly check if OBJECT and OBJECT.somearray exists in somefile.js and push an object item in it. 但是我不知道如何正确检查somefile.js中是否存在OBJECT和OBJECT.somearray并在其中推送一个对象项。

With dart:js you can check the presence of a global variable with : 使用dart:js,您可以使用以下命令检查全局变量的存在:

bool exist = context.hasProperty('OBJECT');
if (exist) {
  final o = context['OBJECT'];
  if (!o.hasProperty('somearray')) {
    o['somearray'] = new JsArray();
  }
}

You are mixing some things up, especially the scope of the function of your JS. 您正在混淆一些事情,尤其是JS功能的范围。 I don't want to make assumptions about your js, but it looks as if you do not properly initialize your OBJECT. 我不想对您的js做出假设,但似乎您没有正确初始化对象。 You want to add something like this to your javascript 您想将类似的内容添加到您的javascript中

function myObject(){
  this.array = []
}

In dart you can, as Felix pointed out in the comments then create this function. 正如Felix在评论中指出的那样,在dart中可以创建此功能。 There are different options. 有不同的选择。 One is to access JS functions via dart:js (see felix comment), another is to use the js-interop library. 一种是通过dart:js访问JS函数(请参阅felix注释),另一种是使用js-interop库。 I am not particularly sure what the differences are but i find the js-interop library to have a much cleaner API ( https://github.com/dart-lang/js-interop ) 我不确定是否有什么区别,但是我发现js-interop库具有简洁的API( https://github.com/dart-lang/js-interop

import 'package:js/js.dart' as js;
var yourObject = js.Proxy(js.context.myObject);
yourObject.array.push("...");

js.interop makes javascript calls available on an object, rather than using callMethod etc. but I guess it relies on dart2js rather than dart only. js.interop使对象可以使用javascript调用,而不是使用callMethod等。但是我猜它依赖dart2js而不是dart。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM