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

dart, dart-js-interop

Solution

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

Problem

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.

Original source