How can I access this from JavaScript via JS-Dart interop?

I need to access the JavaScript this object from a Dart function. I am effectively adding a new method to a JavaScript object using Dart-JS interop. I need to access the properties that are on a JavaScript object from a method defined in Dart.

+6
source share
1 answer

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(); // comes from Dart land }); 
+5
source

Source: https://habr.com/ru/post/949623/


All Articles