2

This should be simple, but I just can't seem to wrap my head around it.

So I have my dartFile.dart and then I have my javaScriptFile.js. How do I link these two so that I can call JavaScript functions declared in my javaScriptFile.js from my dartFile.dart?

I tried to follow the explanation provided in this post, but I guess it was too vague for me :/

Edit: Here's what I tried:

In my javaScriptFile.js, there is nothing but this simple function:

function myFunction() {
  return 4;
}

In my dartFile.dart, there is only this blob of code:

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

void main() {
  print(js.context.myFunction());
}

Following the instructions in the post I mentioned, I added dependencies for js in the pubspec.yaml file. Basically I'm exactly where the asker of the original question was - I can call basic JavaScript functions like alert, but wehn I try to call my function declared in the javaScriptFile.js, I get a 'NoSuchMethodError'

Community
  • 1
  • 1
Peter Bosák
  • 317
  • 2
  • 11
  • Your question should be much more specific about what you try to accomplish and show code that demonstrates what you have tried, and what error you got. – Günter Zöchbauer Aug 09 '14 at 17:53
  • You make a fine point. I tried to keep it simple, but perhaps I should have been more specific. Is it better now? – Peter Bosák Aug 09 '14 at 18:09
  • Why do you need JS if you already can use Dart? – Robert Aug 09 '14 at 18:22
  • Heh, only now that you asked I realized how this must look :D I need to use external libraries written in JavaScript (by someone else of course). I used my own JavaScript file here in this example purely for learning purposes - in order to simplify things as much as possible. – Peter Bosák Aug 09 '14 at 18:37

1 Answers1

3

You can just do it like this:

  1. Make sure you include JS before .dart files or make sure all JS files are loaded before running Scripts from Dart

  2. Contents of the dart file:


import 'dart:js';

void main() {
  var ret = context.callMethod('myFunction', ['a', 'b']);
  var inst = new JsObject(context['someClass'], ['instance']); 
  print(inst);
}
  1. my JS File:

function myFunction() {
  console.log(arguments);
}

function someClass(a) {
  this.a = a;
}

This should give you output like

[object Arguments] // from console.log
[object Object]    // from print()

Regards, Robert

Robert
  • 5,484
  • 1
  • 22
  • 35
  • 1
    Thanks, it works perfectly now! I was puzzled by the "Make sure you include JS before .dart files" for a second, but then I realized you meant the line in the .html file. (And thus, I'm writtin this comment in case anyone else get stuck where I did) – Peter Bosák Aug 10 '14 at 11:32