Call JavaScript from Dart - First Look

UPDATE: This article is deprecated. Dart has an improved Dart-JavaScript interop library, now included in the Dart SDK. Please read about dart:js and how to use it.

If possible, do not use the js package that this blog post talks about. The js package will bloat your code.


---



You can use Dart to access existing JavaScript code, thanks to the Dart-JS Interop package. Call JavaScript functions from Dart, send Dart callbacks to JavaScript, and more!



The Dart core libraries have a lot of functionality provided out of the box (collections, querying the DOM, dates and times, math, and more), so you can get quite far with just the Dart SDK and the many pub packages. However, there are plenty of useful JavaScript libraries that can really help enhance Dart web apps. Luckily, Dart can synchronously talk to JavaScript!

Step 1: Install the js package

Add the following to your pubspec.yaml file:

dependencies:
  js: any

Step 2: Get a JavaScript library

Hugs make you feel better, let's use the hugs.js library:

function Hug(strength) {
  this.strength = strength;
}

Hug.prototype.embrace = function(length) {
  return 'Thanks, that was a good hug for ' + length + ' minutes!';
}

Hug.prototype.patBack = function(onDone) {
  onDone('All done.');
}

Be sure to include the JavaScript files in your main HTML file:

<script src="hugs.js"></script>
<script src="packages/browser/dart.js"></script>
<script src="packages/browser/interop.js"></script>

Step 3: Write Dart code

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

void main() {
  // Grab the context from JS land.
  var context = js.context;
  
  // Use the [] notation to let --minify work.
  // See https://github.com/dart-lang/js-interop/issues/86
  
  // Get a proxy to the JS object.
  var hug = new js.Proxy(context['Hug']);
  
  // Call the embrace method and pass in 10.
  var result = hug['embrace'](10);
  
  query('#output').text = result;
  
  // Call the patBack method and pass in a callback.
  hug['patBack'](new js.Callback.once((msg) {
    query('#output').appendText(' This just in: $msg');
  }));

}

The hug instance is accessed via a js.Proxy object. You can even pass a Dart function as a callback to a JavaScript function!

Summary

Use the Dart-JS interop library to access the billions of existing JavaScript libraries from Dart. Read the article for more details and see examples that use the Twitter API, Google Maps API, and the Google Charts API from Dart. The pub package is open source on Github, and is maintained by Googlers and engineers from the community.


Photo Credit: Gloson cc
Post a Comment

Popular posts from this blog

  • Sponsor:  Register today for  New Game, the conference for HTML5 game developers . Learn from Mozilla, Opera, Google, Spil, Bocoup, Mandreel, Subsonic, Gamesalad, EA, Zynga, and others at this intimate and technically rich conference. Join us for two days of content from developers building HTML5 games today. Nov 1-2, 2011 in San Francisco.  Register now ! This is the second article in a Box2D series, following the Box2D Orientation article. The Box2DWeb port of Box2D contains a nice example to show off the basics of integrating physics simulations into your web app. This post will provide a walkthrough of the example, explaining the high level concepts and code. First, let's see the example in action. The code for the above is open source and available on GitHub. It was adapted from Box2DWeb's example . Animating Before we look at Box2D, it's important to understand how the above simulation is animated. You might think setInterval or setTimeout is
  • In which I port a snazzy little JavaScript audio web app to Dart , discover a bug, and high-five type annotations. Here's what I learned. [As it says in the header of this blog, I'm a seasoned Dart developer. However, I certainly don't write Dart every day (I wish!). Don't interpret this post as "Hi, I'm new to Dart". Instead, interpret this post as "I'm applying what I've been documenting."] This post analyzes two versions of the same app, both the original (JavaScript) version and the Dart version. The original version is a proxy for any small JavaScript app, there's nothing particularly special about the original version, which is why it made for a good example. This post discusses the differences between the two implementations: file organization, dependencies and modules, shims, classes, type annotations, event handling, calling multiple methods, asynchronous programming, animation, and interop with JavaScript libraries. F
  • Angular and Polymer, sitting in a DOM tree, B-i-n-d-i-n-g. First comes components, Then comes elements, Then comes the interop with the node dot bind. Angular , a super heroic MVC framework, and Polymer , polyfills and enhancements for custom elements built on top of Web Components, can live harmoniously in the same app. This post shows you how to connect Angular-controlled components to Polymer-controlled elements via data binding. And we do it all in Dart . Angular and Polymer I get asked "Should I use Angular or Polymer?" a lot. My answer is, "Yes". That is, both libraries have distinct strengths, and you can use both in the same app. Polymer excels at creating encapsulated custom elements. You can use those custom elements in any web app or web page, regardless if that app is built with Angular, Ember, etc. Angular excels at application engineering, with dependency injection, end-to-end testability, routing, and services. Here are som