Callback constructor can pass this from JavaScript. According to the API docs for the 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']); }
Note the use of withThis: true when creating a callback. this from JavaScript is passed as the first argument to the callback function. In this case, I give it the name 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();
source share