Wednesday, September 26, 2012

Use JavaScript code in your Dart apps

You can now use existing JavaScript code with Dart! We've recently released a JavaScript-Dart interop library, one of our developers' most requested features. This is a big milestone for the Dart project.

Using this library, you can proxy JavaScript objects inside Dart code. You can also reach Dart functions from JavaScript code.

Here's an example of wrapping a Google Maps API object:


var canvas = query('#map_canvas');
var googlemaps = js.context.google.maps;
var googlemap = new js.Proxy(googlemaps.Map, canvas);



This code instantiates a JavaScript google.maps.Map object onto the given canvas and returns a proxy to Dart. Note that googlemaps.Map is a proxy to the JavaScript constructor. The resulting googlemap is a proxy to the actual Google Map object in JavaScript.

Here's an example of calling a Dart function from JavaScript:


js.context.handler = new js.Callback.once(display);



var script = new ScriptElement();
script.src
 = 'http://search.twitter.com/search.json?q=dartlang&rpp=10&callback=handler';
document.body.nodes.add(script);



You can read more about using existing JavaScript code inside your Dart apps. As always, please join the discussion at the Dart mailing list or on Stack Overflow. Thanks for trying Dart!