Create js Objects from Dart

1.1k views Asked by At

I have js code that needs to be translatable to Dart:

(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.

2

There are 2 answers

0
Alexandre Ardhuin On

With dart:js you can check the presence of a global variable with :

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

You are mixing some things up, especially the scope of the function of your JS. I don't want to make assumptions about your js, but it looks as if you do not properly initialize your OBJECT. You want to add something like this to your javascript

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

In dart you can, as Felix pointed out in the comments then create this function. There are different options. One is to access JS functions via dart:js (see felix comment), another is to use the js-interop library. 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)

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.