简体   繁体   中英

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

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM