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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With