2
votes

What is the difference between:

context["recentlyUsedStations"] = ["Goetheplatz", "Marienplatz"];

and

context["recentlyUsedStations"] = new JsObject.jsify(["Goetheplatz", "Marienplatz"]);

I am using this on a chrome extension background page and am able to get the values in a popup page in both cases. If I try to change the list, then the first case produces an array of integers (value 0). The second case works okay.

1

1 Answers

3
votes

The first version defines a js variable named recentlyUsedStations with its value set with a js object DartObject containing a reference to the ["Goetheplatz", "Marienplatz"] Dart object. From Js side this variable is almost unusable and should only be used to keep a reference on the Dart object. This way the Dart object can be retrieved by calling context["recentlyUsedStations"].

Without new js.JsObject.jsify(...) :

final a = ['b', 'c'];
js.context['a'] = a;

// unusable wrapper on Js side
// display : [object DartObject]
js.context['console'].callMethod('log', [js.context['a']]);

// the reference is kept
// display : true
print(identical(a, js.context['a']));

The second version defines a js variable named recentlyUsedStations with its value set with a js object that has been created by converting ["Goetheplatz", "Marienplatz"] to an equivalent js array ["Goetheplatz", "Marienplatz"]. This way the data can be used on Js side but it forgets the reference on the original Dart object. So adding an element to the dart List will have no effect on the array on the Js side.

With new js.JsObject.jsify(...) :

final a = ['b', 'c'];
js.context['a'] = new js.JsObject.jsify(a);

// converted to an array on Js side
// display : [b,c]
js.context['console'].callMethod('log', [js.context['a']]);

// the reference has been forgotten
// display : false
print(identical(a, js.context['a']));

// adding an element on the original List has no effect on Js value
a.add('d');
js.context['console'].callMethod('log', [js.context['a']]); // b,c