Using resumable.js from Dart - dart

I am trying to use resumable.js from Dart with this code:
var rs = new JS.JsObject(JS.context['Resumable'], [new JS.JsObject.jsify({
'target':context.server+'/upload'
})]);
files.forEach((file) {
rs.callMethod("addFile",[file]);
});
files variable is defined as List<File> (dart.html.File). When I check properties of rs object with these two lines:
JS.context["console"].callMethod("log",[rs['opts']]);
JS.context["console"].callMethod("log",[rs['files']]);
I find that rs.opts are initialized correctly, but rs.files always contains instances of ResumableFile with length 1. I guess that it is because method addFile expects parameter to be instance of Javascript File but it gets instanceof dart:html.File.
Do you have any idea how to convert dart:html.File to Javascript File or how to pass argument to resumable.js?
I know that I can alternatively use methods assignBrowse and assignDrop, but I would like to stick to my solution.

You have to use JsObject.fromBrowserObject to get the underlying js object.
files.forEach((file) {
rs.callMethod("addFile",[new JsObject.fromBrowserObject(file)]);
});

Related

Dart Flutter: Why use getter instead of setter for Stream Sink?

To my basic understanding of Stream and sink we add data to sink in order to pass it through the stream but to add it we use a getter instead of setter, which I find counter-intuitive (see example below), could you please explain in simple words why is it how it is and not the other way around?
Example:
class BlogPostViewModel {
StreamController<List<BlogPost>> _blogPostListController = StreamController.broadcast();
Stream<List<BlogPost>> get outBlogPostList => _blogPostListController.stream;
Sink<List<BlogPost>> get _inBlogPostList => _blogPostListController.sink; // Here why use get and not a setter?
}
In advance, thank you.
The getter and setter concept is a way to simulate access to a field in a class but control the behavior of this. So behind the scene there can even not be any variable if we want to e.g. have a getter which fetch some data from somewhere each time (please don't do that).
get and set are therefore methods called when we try to get and set the value of this field:
class MyClass {
void get test => print('You called get');
set test(void input) => print('You called set');
}
void main() {
final obj = MyClass();
obj.test; // You called get
obj.test = null; // You called set
}
So in your case, you want to make so when you try to get the "variable" named _inBlogPostList you will instead get the result of _blogPostListController.sink.
The advantage of this is you get a Sink instance which you can call add and close on. If you don't need to close the sink you can instead use a set method to add stuff into the sink like RĂ©mi Rousselet proposes.

How to create a dynamic variable in dart

I am moving java script to dart, in java script I create dynamic variable like
window["text" + pageNumber] = 123;
alert(window["text" + pageNumber]);
How can I do it with dart?
In Dart Window (the type of window) is a class. You can't dynamically add properties to a Dart class.
window["text" + pageNumber] = 123; would work with a Map. Object representation in JS is quite similar to a map and therefore this works there.
If another class implements the [] operator you could call it on instances of that class as well but it would still not add properties. What it actually does just depends on the implementation of the [] operator.
There are probably different ways in Dart to achieve what you want, but you didn't add details about what actual problem you try to solve.
You can use normal global variables in Dart like explained in
Global Variables in Dart.
For your use case you can create a global Map variable this way
final Map<String,int> myGlobals = <String,int>{};
to create a map that stores integer values with string names.
Set values with myGlobals['someName'] = 123; and read them with print(myGlobals['someName']);.
If you need to set a global value that is also available for JS libraries you might use, you can use dart-js-interop
import 'dart:js';
import 'dart:html';
main() {
int pagenumber = 5;
context['Window']['text$pagenumber'] = 123;
window.alert('${context['Window']['text$pagenumber']}');
}
Try it on DartPad.
Hint:
"text" + pageNumber doesn't work when pageNumber is not a string.
In Dart you can't add string and numbers.
"text" + pageNumber.toString() would work but 'text$pagenumber' is a more darty way to do this. In string interpolation toString() is called automatically for you.
See also Dart js-interop not working if .dart file isn't included.

How to omit data type tags in SnakeYaml?

I have the following 1.1 YAML generated by SnakeYaml
'test_jbgrp1':
'tags': []
'jobs':
- 'test_job1'
'reserve': []
'cancel':
- 'max_duration': !!int '1200'
The !!int tag is breaking another (older) piece of software and I have a requirement to remove the tag before writing the file. I don't want to revert to a silly solutions such as writing content to a String and postprocessing it before dumping the file so the question is - is there a setting in Snakeyaml that would remove !!int from the code above?
Assuming you have to remove all occurences of the !!int
You can take a look at the How to skip a property to skip the property or do some transformation using Flexible Scalar Type Customization
In short you configure Yaml instance as below
Yaml yaml = new Yaml(new MyRepresenter());
String output = yaml.dump(new MyJavaBean());
where MyRepresenter is expressed as below
#Override
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property,
Object propertyValue, Tag customTag) {
if (int.class.equals(property.getType())) {//some better condition
//construct NodeTupe as you wish - i.e. keep the element and remove the type
return null;//this will skip the property
} else {
return super
.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
}
}

in Dart, problems when attempting to "register" sub-class with super-class

I wish to have the sub-classes of a super-class "registered" by an arbitrary name - whenever I declare a sub-class I wish to also have it entered into the super-class.sub Map.
Is there any way to accomplish this outside of main()?
// base class
class Mineral{
final String formula;
static Map<String,Mineral> sub = {}
Mineral( this.formula );
}
// sub class - declare and register
class Mica extends Mineral{
Mica( String formula ) : super( formula );
}
Mineral.sub['mica'] = Mica; // oops!
when I run this, I get
Error: line 10 pos 1: unexpected token 'Mineral' Mineral.sub['mica'] = Mica;
assuming that executable code is not allowed outside main().
cannot put within the super-class since other sub-classes may declared later, outside the library.
Dart has no way to run code as part of a library being loaded.
Executable code can only be put inside methods, or in field initializers, and static field initializers are lazy so they won't execute any code until you try to read them.
This is done to ensure quick startup - a Dart program doesn't have to execute any code before starting the main library's "main" method.
So, no, there is no way to initialize something that isn't constant before main is called.
Either
Mineral.sub['mica'] = new Mica();
or
static Map<String,Type> sub = {};
When you assign Mica you assign the Type Mica. new Mica() is an instance of Mica that is of the kind Mineral and can be assigned to the map you declared.
edit
Maybe you want to initialize the sub map:
static Map<String,Mineral> sub = {'mica': new Mica()};
hint: the semicolon is missing in this line in your question.

How to check if two objects are of the same type in Actionscript?

I want to do this in Actionscript:
typeof(control1) != typeof(control2)
to test if two objects are of the same type. This would work just fine in C#, but in Actionscript it doesnt. In fact it returns 'object' for both typeof() expressions because thats the way Actionscript works.
I couldn't seem to find an alternative by looking in the debugger, or on pages that describe typeof() in Actionscript.
Is there a way to get the actual runtime type?
The best way is to use flash.utils.getQualifiedClassName(). Additionally, you can use flash.utils.describeType() to get an XML document the describes more about the class.
Actionscript 3 has an is operator which can be used to compare objects. Consider the following code:
var mySprite:Sprite = new Sprite();
var myMovie:MovieClip = new MovieClip();
trace(mySprite is Sprite);
trace(myMovie is MovieClip);
trace(mySprite is MovieClip);
trace(myMovie is Sprite);
Which will produce the following output:
true
true
false
false
This will work for built-in classes, and classes you create yourself. The actionscript 2 equivalent of the is operator is instanceof.
You'll want to use the Object.prototype.constructor.
From the documentation:
dynamic class A {}
trace(A.prototype.constructor); // [class A]
trace(A.prototype.constructor == A); // true
var myA:A = new A();
trace(myA.constructor == A); // true
(Conveniently, this is also how to check types in javascript, which is what originally led me to this in the docs)
So, to test this out before I posted here, I tried it in an app I have, in a class called Player. Since the prototype property is static, you can't call it using "this" but you can just skip the scope identifier and it works:
public function checkType():void {
trace(prototype.constructor, prototype.constructor == Player);
// shows [class Player] true
}
Is there a way to get the actual runtime type?
Yes.
var actualRuntimeType:Class = Object(yourInstance).constructor;
Some other answers already refer to .constructor, but you can't always directly access .constructor in ActionScript 3. It is only accessible on dynamic classes, which most classes are not. Attempting to use it on a regular class will cause a compile-time error under the default settings.
However, because every class inherits from Object, which is dynamic, we can look up their .constructor property just by casting an instance to Object.
Therefore if we are not interested in subclasses, we can confirm that two instances are of exactly the same class by simply evaluating this:
Object(instanceA).constructor === Object(instanceB).constructor;
I learned of this from the post "Get the class used to create an object instance in AS3" by Josh Tynjala.
A even simpler alternative that also works for me is just:
var actualRuntimeType:Class = yourInstance["constructor"];
The runtime is entirely capable of giving you the .constructor, it's just that the compiler complains if you use that syntax. Using ["constructor"] should produce the same bytecode, but the compiler isn't clever enough to stop you.
I included this second because it hasn't been tested anywhere except my current Flash environment, whereas several users have said that the method described above works for them.
If you want to account for inheritance, then you might want to try something like this:
if (objectA is objectB.constructor || objectB is objectA.constructor)
{
// ObjectA inherits from ObjectB or vice versa
}
More generally, if you want to test whether objectA is a subtype of objectB
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
...
if (objectA is getDefinitionByName(getQualifiedClassName(objectB)))
{
...
}
Object obj = new Object();
Object o = new Object();
if(o.getClass().getName().endsWith(obj.getClass().getName())){
return true;
}else{
return false;
}

Resources