Using Dart classes from JavaScript - dart

I have a Dart class (foo.dart):
class Foo {
void talk() {
print('Hello');
}
}
After compiling foo.dart to JavaScript, I'd like to be able to use Foo like this:
var foo = new Foo(); // from foo.dart.js
foo.talk() // prints "Hello"
My questions:
Is this currently possible?
If so, how?
If not, what plans, if any, are in place to make it possible?
The dart:js library documentation states:
This library does not yet make Dart objects usable from JavaScript, their methods and proeprties [sic] are not accessible, though it does allow Dart functions to be passed into and called from JavaScript.
That word "yet" offers some hope, but I've found very little on this topic anywhere else.
Edit:
I do realize it's possible to call Dart functions from JavaScript using dart2js. However, what I'm trying to do is somewhat different. I'd like to be able to access all of the functionality of a Dart class from JavaScript.

Due to tree-shaking and minification this is normally not possible. If you have a Dart application (with a main() then you can make a Dart function available to be called from JavaScript (see How to call a Dart function from Javascript? for an example).
As far as I know there are plans to support your requirement but I have no idea about progress or when such a feature might be available.
This is the related project https://github.com/dart-lang/js-interop

Related

A more standard __attribute__((warning("msg"))

In my C++ library I have a function that is still there, 1) for debugging 2) for small operations.
The function is basically a very slow fallback of more efficient versions.
(think of a loop of individual assigments vs memcpy for example)>
For this reason I would like to emit a warning as soon the function is invoked instantiated directly or indirectly. Without a warning it is not easy to test if the function is being invoked instantiated, because the function might be called instantiated trough several layers of template code.
I found that GCC's __attribute__((warning("slow function!"))) does the job quite well.
template<class T>
__attribute__((warning("careful this fun is very slow, redesign your algorithm")))
void slow_function(T){...}
However it is not standard or compatible with clang.
Is there a better alternative for this kind of compile time warning?
It looks like there is a standard [[deprecated("msg")]] attribute that also does the job, the problem is that it is confusing because there is nothing deprecated about this function, it is there for convenience.
There is also, I found recently a #pragma poison that might be applicable here, but I don't understand how it is used, besides the function is actually a member function of a template class, the examples do not consider this case. https://www.fluentcpp.com/2018/09/04/function-poisoning-in-cpp/

Dart js-interop and overloaded methods

How do you handle interfacing with JS libraries that have overloaded methods?
For example Leaflet.js has both of the following defined for the Map object:
openPopup(popup); // opens the given popup
openPopup(html, LatLng, popOptions); // creates a popup with the html at the location, using the popup options.
What I've come up with is:
#JS("L.Map")
class Map {
/* code */
external Map openPopup(dynamic popup, [LatLng coords, PopupOptions opts]);
/* code */
}
Is there a better way? Note: this seems to work but the analyzer complains: The method openPopup is not defined for the class Map.
Dart: 1.17.1
package:js-0.6.0
So far I have not been able to specify a different name for an instance member/method using the JS() directive which is a big issue especially for javascript object that have method names that clash with Dart keywords (such as 'catch' in a javascript Promise). I ended up using plain dart:js. And anyway even when using package/js, I ended up adding another layer to make the api more dartish (especially with callbacks and promise) especially to enforce argument types.
What I would expect would be to be able to do (in your example)
#JS("L.Map")
class Map {
JS('openPopup')
external Map openPopupHtml(String html, [LatLng coords, PopupOptions opts]);
JS('openPopup')
external Map openPopup(Popup popup);
}
but that does not seem to work. Maybe should it be considered as a feature enhancement.

Can I omit the class name when calling a static method?

In F#, can I omit the class name when calling a static method?
Example:
In C#, I can do something like:
using static Bizmonger.Patterns.MessageBus;
...
Publish("SOME_MESSAGE");
instead of:
MessageBus.Publish("SOME_MESSAGE");
Can I do something like this in F#?
In F#, you can use open on namespaces (just like using in C#) or on modules (which is useful when the API you are calling has been written in F#), but not on static classes (which is what you'd need when calling C# libraries).
One thing that you can do though to make the code a bit shorter is to define a type alias:
type M = Bizmonger.Patterns.MessageBus;
// Now you can write just
M.Publish("SOME_MESSAGE")
// Rather than writing the full
MessageBus.Publish("SOME_MESSAGE");
There is a feature request on the F# UserVoice to allow using open on static classes (just like in C#) and so if you'd like this to happen, please upvote and comment there.
I also learned that I could implement a function to serve as a wrapper for clients to call instead.
Create a wrapper function
module Messages
open Bizmonger.Patterns
let Publish (message:string, payload:_) =
MessageBus.Publish(message, payload)
Client
Then a client can now invoke a function without specifying a class name.
open Messages
...
Publish("SOME_MESSAGE", null);

What does external mean in Dart?

What does external mean in Dart? For example: external DateTime._now();
I'm new to Dart, I can't find documentation for external, so can you give an example to help explain?
9.4 External Functions
An external function is a function whose body is provided separately from its
declaration. An external function may be a top-level function (17), a method
The body of the function is defined somewhere else.
As far as I know this is used to fix different implementations for Dart VM in the browser and Dart VM on the Server.
When we make an external function inside a class like toString()
external String toString();
means this method is abstract and the child of the parent class will add the function body, that's because in Dart we only can make an abstract class.
Summary:
external function = abstract function in not abstract classes
I don't think external keyword is meant to be used to mark methods as abstract, even if that's possible
It's enough to leave a method with no implementation to set it abstract, inside an abstract class
It's the equivalent of declare in TypeScript, and extern in C#, those are used for interoperability with other runtimes, which means you're telling the compiler "Don't worry about this method's implementation, I promise it will exist at runtime", the runtime may be in C or Javascript or whatever
In case, if you are wondering why or where should I even use external keyword, here is a one more example for Flutter.
class MyStruct extends Struct {
#Int32()
external int a;
#Float()
external double b;
external Pointer<Void> c;
}
Sometimes, but not often when you play with native libraries, in this case with Struct to access native struct's field in memory. Under Struct We must declare all fields as external because it will be external fields from dart:ffi (C / C++).
So, external is more than just way to declare "abstract method".
9.4 External Functions
An external function is a function whose
body is provided separately from its
declaration.
What this does mean is that you define the function, but without implementation. It's exactly how you define the abstract method, but the only difference is that with external you don't implement the method in dart but in C or something else.
Something like String class it can be considered as external functions except that the String class it marked with #pragma('vm:entry-point') which make the entire class use native code.
See the following example to understand:
This dart's side.
https://github.com/dart-lang/sdk/blob/main/sdk/lib/core/string.dart#L711
This the implementation in C++.
https://github.com/dart-lang/sdk/blob/main/runtime/lib/string.cc#L467-#L472
In my opinion it is an equivalent of Java native keyword. For example, since current time milliseconds is implemented differently on Android, iOS, Linux etc, DateTime.now().millisecondsSinceEpoch will be linked to different implementations at runtime. So it is not initially known how this method will look like. For this reason it is marked as external meaning it is platform dependent.

Using Dart as a DSL

I am trying to use Dart to tersely define entities in an application, following the idiom of code = configuration. Since I will be defining many entities, I'd like to keep the code as trim and concise and readable as possible.
In an effort to keep boilerplate as close to 0 lines as possible, I recently wrote some code like this:
// man.dart
part of entity_component_framework;
var _man = entity('man', (entityBuilder) {
entityBuilder.add([TopHat, CrookedTeeth]);
})
// test.dart
part of entity_component_framework;
var man = EntityBuilder.entities['man']; // null, since _man wasn't ever accessed.
The entity method associates the entityBuilder passed into the function with a name ('man' in this case). var _man exists because only variable assignments can be top-level in Dart. This seems to be the most concise way possible to use Dart as a DSL.
One thing I wasn't counting on, though, is lazy initialization. If I never access _man -- and I had no intention to, since the entity function neatly stored all the relevant information I required in another data structure -- then the entity function is never run. This is a feature, not a bug.
So, what's the cleanest way of using Dart as a DSL given the lazy initialization restriction?
So, as you point out, it's a feature that Dart doesn't run any code until it's told to. So if you want something to happen, you need to do it in code that runs. Some possibilities
Put your calls to entity() inside the main() function. I assume you don't want to do that, and probably that you want people to be able to add more of these in additional files without modifying the originals.
If you're willing to incur the overhead of mirrors, which is probably not that much if they're confined to this library, use them to find all the top-level variables in that library and access them. Or define them as functions or getters. But I assume that you like the property that variables are automatically one-shot. You'd want to use a MirrorsUsed annotation.
A variation on that would be to use annotations to mark the things you want to be initialized. Though this is similar in that you'd have to iterate over the annotated things, which I think would also require mirrors.

Resources