3

Trying to call a javascript method that required a typed array.

var arrayData = js.array(new Uint8Array.fromList(data.charCodes));

Using js.array does not proxy it the way I was expecting, how could I pass the typed array as a typed array to a javascript method in dart?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
adam-singer
  • 4,489
  • 4
  • 21
  • 25

2 Answers2

3

You can instantiate ArrayBuffer and Uint8Array javascript objects directly from Dart.

If you need only a Uint8Array javascript object :

js.scoped(() {
  final charCodes = "test".charCodes;
  final bufView = new js.Proxy(js.context.Uint8Array, js.array(charCodes));

  // do something with bufView
});

If you need an ArrayBuffer javascript object:

js.scoped(() {
  final charCodes = "test".charCodes;
  final buf = new js.Proxy(js.context.ArrayBuffer, charCodes.length);
  final bufView = new js.Proxy(js.context.Uint8Array, buf)
    ..set(js.array(charCodes));

  // do something with buf
});

Basically, each time you need to use the new javascript operator, you have to use new js.Proxy(construtor,...).

WARNING : Until a new version has landed containing the pull-request #34 of js-interop, you have to use the following dependency to run the above code snippet.

dependencies:
  js:
    git: git://github.com/dart-lang/js-interop.git
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
  • I checked your commit out, that should also apply to Uint16Array, Uint32Array, correct? – adam-singer Dec 18 '12 at 16:24
  • Yes, it should work. It's not a bug in [js-interop](https://github.com/dart-lang/js-interop) but a workaround because some javascript functions (like `ArrayBuffer` or `Uint8Array`) in Chrome have not `apply` function and could not be instantiate. – Alexandre Ardhuin Dec 18 '12 at 16:33
2

A solution found was to create a utils.js and include the constructors for objects not loaded in the js.context.

utils.js:

var xArrayBuffer=function(length) {
    return new ArrayBuffer(length); 
};

var xUint8Array=function(buf) {
    return new Uint8Array(buf);
};

Include the utils.js in your index.html

  <body>
    <script src="utils.js"></script>
    <script src="dart.js"></script>
    <script src="example.dart.js"></script>
  </body>

Then call from a js.scoped closure. example.dart

  js.scoped(() {
    var jscore = js.context.jscore;        
    var buf = js.context.xArrayBuffer(data.charCodes.length);
    var bufView = js.context.xUint8Array(buf);

    for (var i = 0; i < data.charCodes.length; i++) {
      bufView[i] = data.charCodeAt(i);
    }

    jscore.writeArrayBuffer(buf);
  });
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
adam-singer
  • 4,489
  • 4
  • 21
  • 25