soin08
soin08

Reputation: 76

Inherit Dart class from a JS class?

I have an HTML5 game made using CreateJS js library. I would like to rewrite it using Dart, but most of my objects inherit from CreateJS objects (e.g. Container). Would I be able to save such inheritance? Is there a nice way of using Dart with other js libraries designed to simplify drawing on canvas?

Upvotes: 1

Views: 437

Answers (1)

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76353

A Dart class cannot directly extend a Javascript class. However, you can customize your Javascript object by setting method that will execute Dart code.

For instance, let suppose you have a Child Javascript class that extends Container class :

function Container(){}
Container.prototype.callSayHello = function(){ this.sayHello(); }
Container.prototype.sayHello = function(){ alert("hello from JS"); }

function Child(){}
Child.prototype = new Container();

On Dart side you can create a Child and define a sayHello method on it overriding sayHello from Container :

import 'dart:html';
import 'package:js/js.dart' as js;

main(){
  // with sayHello overriding
  js.scoped((){
    final child = new js.Proxy(js.context.Child);
    child.sayHello = new js.Callback.many(() {
      window.alert("hello from Dart");
    });
    child.callSayHello(); // displays "hello from Dart"
  });

  // without sayHello overriding
  js.scoped((){
    final child = new js.Proxy(js.context.Child);
    child.callSayHello(); // displays "hello from JS"
  });
}

Upvotes: 2

Related Questions