Pergunta

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?

Foi útil?

Solução

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

Outras dicas

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);
  });
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top