2

I'm constructing two JS object in Dart. In JS, they are constructed with Object.create():

var wavesurfer1 = Object.create(WaveSurfer);
var wavesurfer2 = Object.create(WaveSurfer);

This is what I think is Dart equivalent:

var wavesurfer1 = context['WaveSurfer'];
var wavesurfer1 = context['WaveSurfer'];

But, I found that the two objects in Dart appear to be the same. When I call a function in one object it gets triggered in both. This does not happen in the JS code. I suspect that Object.create() should not be written as context[''] in Dart. If this is true, I'm not able to find an example in dartlang.org or stackoverflow.com for how to correctly translate this expression to Dart. You can see the JS source code for WaveSurfer here.

1 Answer 1

4

With context['WaveSurfer'] you get a JsObject corresponding to the Js WaveSurfer and not to a new object.

To do the Dart equivalent of your pasted JS code :

import 'dart:js';

var wavesurfer = context['WaveSurfer'];
var wavesurfer1 = context['Object'].callMethod('create', [waveSurfer]);
var wavesurfer2 = context['Object'].callMethod('create', [waveSurfer]);

See Using JavaScript from Dart.

If you find the usage of dart:js to hard and verbose you can use package:js that provides a simplier API (but with a larger JS generated size) :

import 'package:js/js.dart';

var wavesurfer1 = context.Object.create(context.WaveSurfer);
var wavesurfer2 = context.Object.create(context.WaveSurfer);
Sign up to request clarification or add additional context in comments.

3 Comments

Alexandre. I tried this before but I get this expection: Exception: TypeError: Object prototype may only be an Object or null.
Sorry. I misread your code. Thank you for taking the time to answer my question.
Alexandre. I found the compiled JS code behaves differently. It appears to create one object from the two constructors. Is this a bug in dart2js?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.