I am planing to use semantic ui modal has anyone any idea, how to interoperate with dart?
Use the js package to interoperate. First, add the package as a dependency. Then, wrap the JavaScript that you want to use from Dart. Here's an example allowing you to use jQuery's $(...).addClass(...) in Dart:
#JS()
library jquery;
import 'package:js/js.dart';
// Calls invoke JavaScript `JSON.stringify(obj)`.
#JS("\$")
external ElementSet $(String selector);
#JS()
class ElementSet {
external addClass(String className);
}
If you import this file, you can now do:
$('#output').addClass("red");
That example is, of course, quite useless — Dart already allows you to modify HTML classes with better readability and flexibility (e.g. querySelector('#output').classes.add("red")).
But in your case, it starts to make sense. You would implement modal() and go from there.
(I would give you an example of how to implement modal, but I wasn't able to install semantic ui on my workstation for 10+ minutes and then I gave up. So I used the jQuery.addClass example instead.)
It's not that easy. There are two or three pub packages available but they are outdated and incomplete.
I did it this way in Dart 2 (AngularDart 5):
import 'dart:js';
// somewhere in the component:
context
.callMethod(r'$', [modalSelector])
.callMethod('modal', [new JsObject.jsify({
'onApprove': new JsFunction.withThis((element){
// do something on approve
})
})])
.callMethod('modal', ['show']);
This Dart code is equivalent to this Javascript code:
$(modalSelector).modal({
'onApprove': function(element){
// do something on approve
})
.modal('show');
As you may see, you have to call the jQuery framework through the JS module.
Related
If I want to use Dart to create a js library, how can I export Dart classes and functions for use in javascript?
Is there something similar to scala.js, like this?
#JSExport
class Hello{
num x = 0
Hello(this.x)
}
So that in javascript, users can instantiate it as var hi = new Hello(1)
In case this is still relevant: You can use the dart2js compiler, which will compile your dart code down to ES.
I want to use the Smoke package and it worked (without using a transformer just in debug mode) on the server side.
On the client side Smoke is already used by Polymer and when I use a method like assert(sk.isSubclassOf(type, Message)); it fails because internal it checks against the _parents collection and this contains only Polymer elements used on my page but none of my other (pure Dart) classes.
How do I initialize Smoke so it recognizes my other classes too.
I got it working using a custom main() for my Polymer entry page.
import 'package:smoke/mirrors.dart' as skm;
import 'package:polymer/polymer.dart';
void main() {
skm.useMirrors(); // worked on the server side without calling this method
initPolymer().run(() {});
}
I have a Java 7 project which makes a lot of use of Javascript for scripting various features. Until now I was using Rhino as script engine. I would now like to move to Java 8, which also means that I will replace Rhino by Nashorn.
How compatible is Nashorn to Rhino? Can I use it as a drop-in replacement, or can I expect that some of my scripts will not work anymore and will need to be ported to the new engine? Are there any commonly-used features of Rhino which are not supported by Nashorn?
One problem is that Nashorn can no longer by default import whole Java packages into the global scope by using importPackage(com.organization.project.package);
There is, however, a simple workaround: By adding this line to your script, you can enable the old behavior of Rhino:
load("nashorn:mozilla_compat.js");
Another problem I ran into is that certain type-conversions when passing data between java and javascript work differently. For example, the object which arrives when you pass a Javascript array to Java can no longer be cast to List, but it can be cast to a Map<String, Object>. As a workaround you can convert the Javascript array to a Java List in the Javascript code using Java.to(array, Java.type("java.util.List"))
To use the importClass method on JDK 8, we need to add the following command:
load("nashorn:mozilla_compat.js");
However, this change affect the execution on JDK 7 (JDK does not gives support to load method).
To maintain the compatibility for both SDKs, I solved this problem adding try/catch clause:
try{
load("nashorn:mozilla_compat.js");
}catch(e){
}
Nashorn can not access an inner class when that inner class is declared private, which Rhino was able to do:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.run();
}
public void run() {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
Inner inner = new Inner();
engine.put("inner", inner);
try {
engine.eval("function run(inner){inner.foo(\"test\");} run(inner);");
} catch (ScriptException e) {
e.printStackTrace();
}
}
private class Inner {
public void foo(String msg) {
System.out.println(msg);
}
}
}
Under Java8 this code throws following exception:
javax.script.ScriptException: TypeError: kz.test.Test$Inner#117cd4b has no such function "foo" in <eval> at line number 1
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:564)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:548)
I noticed that Rhino didn't have a problem with a function called 'in()' (although 'in' is a reserved JavaScript keyword).
Nashorn however raise an error.
Nashorn cannot call static methods on instances! Rhino did this, therefore we had to backport Rhino to Java 8 (Here's a short summary: http://andreas.haufler.info/2015/04/using-rhino-with-java-8.html)
Nashorn on Java8 does not support AST. So if you have Java code that inspects the JS source tree using Rhino's AST mechanism , you may have to rewrite it (using regex maybe) once you port your code to use Nashorn.
I am talking about this API https://mozilla.github.io/rhino/javadoc/org/mozilla/javascript/ast/AstNode.html
Nashorn on Java9 supports AST though.
One feature that is in Rhino and not Nashorn: exposing static members through instances.
From http://nashorn-dev.openjdk.java.narkive.com/n0jtdHc9/bug-report-can-t-call-static-methods-on-a-java-class-instance : "
My conviction is that exposing static members through instances is a
sloppy mashing together of otherwise separate namespaces, hence I
chose not to enable it.
I think this is deeply wrong. As long as we have to use two different constructs to access the same java object and use package declarations unnecessarily in javascript, code becomes harder to read and write because cognitive load increases. I will rather stick to Rhino then.
I have not found a workaround for this obvious "design bug" yet.
What is the difference between show and as in an import statement?
For example, what's the difference between
import 'dart:convert' show JSON;
and
import 'package:google_maps/google_maps.dart' as GoogleMap;
When do I use show and when should I use as?
If I switch to show GoogleMap all references to GoogleMap (e.g. GoogleMap.LatLng) objects are reported as undefined.
as and show are two different concepts.
With as you are giving the imported library a name. It's usually done to prevent a library from polluting your namespace if it has a lot of global functions. If you use as you can access all functions and classes of said library by accessing them the way you did in your example: GoogleMap.LatLng.
With show (and hide) you can pick specific classes you want to be visible in your application. For your example it would be:
import 'package:google_maps/google_maps.dart' show LatLng;
With this you would be able to access LatLng but nothing else from that library. The opposite of this is:
import 'package:google_maps/google_maps.dart' hide LatLng;
With this you would be able to access everything from that library except for LatLng.
If you want to use multiple classes with the same name you'd need to use as. You also can combine both approaches:
import 'package:google_maps/google_maps.dart' as GoogleMap show LatLng;
show case:
import 'dart:async' show Stream;
This way you only import Stream class from dart:async, so if you try to use another class from dart:async other than Stream it will throw an error.
void main() {
List data = [1, 2, 3];
Stream stream = new Stream.fromIterable(data); // doable
StreamController controller = new StreamController(); // not doable
// because you only show Stream
}
as case:
import 'dart:async' as async;
This way you import all class from dart:async and namespaced it with async keyword.
void main() {
async.StreamController controller = new async.StreamController(); // doable
List data = [1, 2, 3];
Stream stream = new Stream.fromIterable(data); // not doable
// because you namespaced it with 'async'
}
as is usually used when there are conflicting classes in your imported library, for example if you have a library 'my_library.dart' that contains a class named Stream and you also want to use Stream class from dart:async and then:
import 'dart:async';
import 'my_library.dart';
void main() {
Stream stream = new Stream.fromIterable([1, 2]);
}
This way, we don't know whether this Stream class is from async library or your own library. We have to use as :
import 'dart:async';
import 'my_library.dart' as myLib;
void main() {
Stream stream = new Stream.fromIterable([1, 2]); // from async
myLib.Stream myCustomStream = new myLib.Stream(); // from your library
}
For show, I guess this is used when we know we only need a specific class. Also can be used when there are conflicting classes in your imported library. Let's say in your own library you have a class named CustomStream and Stream and you also want to use dart:async, but in this case you only need CustomStream from your own library.
import 'dart:async';
import 'my_library.dart';
void main() {
Stream stream = new Stream.fromIterable([1, 2]); // not doable
// we don't know whether Stream
// is from async lib ir your own
CustomStream customStream = new CustomStream();// doable
}
Some workaround:
import 'dart:async';
import 'my_library.dart' show CustomStream;
void main() {
Stream stream = new Stream.fromIterable([1, 2]); // doable, since we only import Stream
// async lib
CustomStream customStream = new CustomStream();// doable
}
as and show keywords used with library import statement. These two keywords are optional with import keyword, But using these keywords you can provide convenience and additional information about your library importing.
show
show give restrictions to access only specific class of that library.
import 'dart:convert' show JSON;
Above dart:convert library contains more than 5 types of converters. (ascii,Base64,Latin1,Utf8 & json are some of them).
But with using show keyword you will give your application source file to access only that JSON converter class only.
warning !! :- if you try to access any other converters like ascii, Base64 or Latin1, you will get an exception.
Because using show keyword you give an restriction for only access Json class in that library api.
So if your source file want to access all the class in that library, you cannot define show keyword for that library importing.
as
Provide additional namespace for library members.
This as keyword is mostly used when a library that contains lot of global functions.
You will access static members of a library by Using the class name and . (dot operator).
eg:- ClassName.staticFun()
And also you will access instance methods and variables by using object name and . (dot operator) eg:- obj.instanceFunc()
And also library source file can have global functions. and we will access them by their name without any parental membership. eg:- func()
So when we access global functions of a different library inside our source file, we didnt have a way to seperatly identified that global function as seperate function of a different library.
But using as keyword, we can add namespace before accessing global functions of that library.
See below example to understanding real benefit of as keyword. 👇
import 'package:http/http.dart' as http;
http library contains lot of global functions. Below shows list of global functions in http library.
Accessing above http library global functions without http namespace.( import 'package:http/http.dart'; )
eg:-
1. get("url")
2. post("url")
Accessing above http library global functions with http namespace. ( import 'package:http/http.dart'as http; )
eg:-
1. http.get("url")
2. http.post("url")
So using as keyword , makes it easy to identify global functions of a different library separated from our source files' global functions.
I prefer the dart document, it's described in Libraries and visibility section.
import as: Specifying a library prefix, for example when import two libraries which has the same function name, then we can give them a prefix to specify the library.
import show: This is used to import part of the library, show only import one name of the library.
import hide: This is another one which is the opposite of the show, hide import all names except the name specified in the hide.
I've tried to bind a custom event handler to a WebComponent that has an EventStreamProvider exposed via a getter, but it comes back with "Class 'DivElement' has no instance getter 'onMainAction'.".
Trimmed down component .dart code...
import 'dart:html';
import 'dart:async';
import 'package:web_ui/web_ui.dart';
class SegmentedButtonsListComponent extends WebComponent {
static const EventStreamProvider<CustomEvent> mainActionEvent = const EventStreamProvider<CustomEvent>("MainActionEvent");
Stream<CustomEvent> get onMainAction => mainActionEvent.forTarget(this);
}
Trimmed usage of component…
<x-segmented-buttons-list id="segmented-buttons-list" on-main-action="eventHandler($event)"></x-segmented-buttons-list>
Trimmed code from main.dart…
import 'dart:html';
import 'dart:async';
import 'package:web_ui/web_ui.dart';
const EventStreamProvider<CustomEvent> mainActionEvent = const EventStreamProvider<CustomEvent>("MainActionEvent");
void eventHandler(CustomEvent event) {
print("""
Yabba Dabba Doo!
Type: ${event.type}
Detail: ${event.detail}
""");
}
void main() {
mainActionEvent.forTarget(query('#segmented-buttons-list')).listen(eventHandler);
}
The "MainActionEvent" custom events are being dispatched by components instantiated within this "list" component.
As you can see from the above example I can catch the events if I create an EventStreamProvider in main.dart and target the component, that works fine (but by-passes the Stream getter in the component).
It would be great though if I could dispense with the EventStreamProvider in main.dart and simply bind to the onMainEvent getter on the component.
Is that possible?
Update 2013-05-05:
Siggi explains below that at present it is not possible to do this, but there is a way to reference the component's CustomEventProvider's getter via the element's xtag.
I found that I had to use a Timer to query the DOM after main() has completed because xtags aren't populated until the main() event loop has finished.
void postMainSetup() {
query('#segmented-buttons-list').xtag.onMainAction.listen(eventHandler);
}
void main() {
Timer.run(postMainSetup);
}
With the above setup a new CustomEventProvider isn't needed to monitor the component.
Good question!
I see a couple parts to this question:
using custom events directly on a component: Currently web_ui uses different objects to represent your component and the actual dom element it represents. In the future, we plan to extend directly from "DivElement" instead of "WebComponent" and that will allow you to do what you wrote.
Meanwhile, you'll have to be more explicit when you want to use the host or shadow root of your component. In your example, it seems like you want to attach the event to the host, so you would need to write something more like this:
Stream<CustomEvent> get onMainAction => mainActionEvent.forTarget(this.host);
using 'on-someting-foo' syntax in a component: you probably found a bug/missing feature =). Currently we treat attributes in a special way and bind their values to fields of a component if we identify that the target was corresponds to a component. We do this for value bindings, but not yet for binding custom events. A workaround before this feature is added, would be to query for your element and attach the event by hand:
query('#host-node').xtag.onMainAction.listen(...);