I need to access a JavaScript object's this
from a Dart function. I'm effectively adding a new method to a JavaScript object, via Dart-JS interop. I need to access properties that are on the JavaScript object from the method defined in Dart.
Asked
Active
Viewed 379 times
6

Seth Ladd
- 112,095
- 66
- 196
- 279
1 Answers
5
The Callback
constructor can pass the this
from JavaScript. According to the API docs for Callback:
new Callback.many(Function f, {bool withThis: false})
new Callback.once(Function f, {bool withThis: false})
Here is an example:
Dart code:
import 'dart:html';
import 'package:js/js.dart' as js;
void main() {
var greeter = js.context['greeter'];
var msg = greeter['greet']('Bob');
greeter['doCoolStuff'] = new js.Callback.many(doCoolStuff, withThis: true);
}
doCoolStuff(jsThis) {
print(jsThis['msg']);
}
Notice the use of withThis: true
when creating the Callback. The this
from JavaScript is passed in as the first argument to the callback function. In this case, I give it a name of jsThis
.
JavaScript code:
function Greeter() {
this.msg = 'hello';
var that = this;
document.getElementById('clickme').addEventListener('click', function() {
that.doCoolStuff();
});
}
Greeter.prototype.greet = function(name) {
return this.msg + ' ' + name;
}
var greeter = new Greeter();
document.getElementById('clickme').addEventListener('click', function() {
greeter.doCoolStuff(); // comes from Dart land
});

Florian Loitsch
- 7,698
- 25
- 30

Seth Ladd
- 112,095
- 66
- 196
- 279