I have a document class with this function on it, it targets a symbol with an instance name of scene4_headlights on the stage:
function accUpdate(e:AccelerometerEvent):void{
scene4_headlights.rotation += (e.accelerationX*10);
}
But I keep getting error 1120: Access of undefined property scene4_headlights even though I have a symbol on the stage with the instance name of scene4_headlights..
Help?
Here you go:
package {
import flash.sensors.Accelerometer;
import flash.events.AccelerometerEvent; //importing everything you need is cruicial
import flash.display.MovieClip;
public class CustomClassName extends MovieClip //your custom class can extend the type of class you used to create your scene4_headlights instance (some prefer using Sprite when the timeline is not required)
{
private var accelerometer = new Accelerometer(); //declare a variable data type: Accelerometer
public function CustomClassName() {
// constructor code
accelerometer.addEventListener(AccelerometerEvent.UPDATE, accUpdate); // add an eventlistener to the variable you just created
}
public function accUpdate(e:AccelerometerEvent): void //declare the function handling the eventlistener
{
scene4_headlights.rotation += (e.accelerationX*10);
trace("The function accUpdate is linked properly"); //trace is your friend
}
}
}
Related
I'm able to do something like the following in TypeScript
class Foo {
private constructor () {}
}
so this constructor is accessible only from inside the class itself.
How to achieve the same functionality in Dart?
Just create a named constructor that starts with _
class Foo {
Foo._() {}
}
then the constructor Foo._() will be accessible only from its class (and library).
A method without any code must be something like this
class Foo {
Foo._();
}
Yes, It is possible, wanna add more information around it.
A constructor can be made private by using (_) underscore operator which means private in dart.
So a class can be declared as
class Foo {
Foo._() {}
}
so now, The class Foo doesn't have a default constructor
Foo foo = Foo(); // It will give compile time error
The same theory applied while extending class also, It's also impossible to call the private constructor if it declares in a separate file.
class FooBar extends Foo {
FooBar() : super._(); // This will give compile time error.
}
But both above functionality works if we use them in the same class or file respectively.
Foo foo = Foo._(); // It will work as calling from the same class
and
class FooBar extends Foo {
FooBar() : super._(); // This will work as both Foo and FooBar are declared in same file.
}
you can create following class in order to get a singleton instance
class Sample{
factory Sample() => _this ??= Sample._();
Sample._(); // you can add your custom code here
static Sample _this;
}
Now in the main function you can call the sample constructor
void main(){
/// this will return the _this instace from sample class
Sample sample = Sample();
}
just use abstract class.
Because you can't instantiate abstract class
JavaSscript:
class MyClass {
constructor() {
console.log("MyClass instance created");
this.answer = 42;
}
}
let example = new MyClass();
console.log(example.answer);
Dart:
#JS()
library interop_test;
import 'package:js/js.dart';
#JS()
class MyClass {
external int get answer;
external set answer(int value);
}
Creating an instance of the the interop class MyClass as
MyClass myClass = MyClass();
results in:
EXCEPTION: TypeError: dart.global.MyClass is not a constructor
I've also tried to add a external MyClass(); and external factory MyClass(); to the #JS() annotated class, but got the same message. If I add #anonymous annotation to the interop class, the exception goes away, but I can't access instance members. (But I don't see why this would need the anonymous annotation)
I'm using dart 2.0.0, angular 5.0.0, js 0.6.1+1 and dartdevc through webdev.
Normally JS interop would rely on function hoisting to ensure that an old-style JS class was in scope. ES6 classes however aren't hoisted and aren't available where Dart expects them to be. There are several different ways you can make the class available to Dart:
Placing the class object on the window
This places the class in the same scope that a function definition would be hoisted to. In JavaScript:
class MyClass { ... }
window.MyClass = MyClass;
Creating a module object
You can also place the class in a sort of pseudo module or namespace. In JavaScript:
class MyClass { ... }
var myModule = { MyClass: MyClass };
Which is then accessible at myModule.myClass in Dart:
#JS('myModule.myClass')
class MyClass { ... }
I want to write some unit tests around an abstract Uploader class that I have written like so:
abstract class Uploader {
Future<StreamSubscription> subscribe(String filename, void onEvent(Event event));
}
class FirebaseUploader implements Uploader {
Future<StreamSubscription> subscribe(String filename, void onEvent(Event event)) async {
String userId = await auth.signInAnonymously();
DatabaseReference databaseReference = _databaseReference(userId, filename);
return databaseReference.onValue.listen(onEvent);
}
}
class UploaderMock implements Uploader {
Future<StreamSubscription> subscribe(String filename, void onEvent(Event event)) async {
Event event = new Event(); // The class 'Event' doesn't have a default constructor.
return Future.value(null);
}
}
The trouble is, I can't work out how to create my own Events in my UploaderMock, so I can call onEvent. If I try to create a new Event(), I get the following error:
The class 'Event' doesn't have a default constructor.
This is because Event has a private constructor:
Event._(this._data) : snapshot = new DataSnapshot._(_data['snapshot']);
This makes sense for production, but it doesn't really work for testing.
Any ideas? How can I test code that uses StreamSubscription?
You can implements Event on a custom class.
class Bar {
Bar._() {}
}
class Foo implements Bar {
Foo();
}
You can't, but you can make them public and annotate it with
#visibleForTesting to get an DartAnalyzer warning when they are
accessed from code that is not in in the same library or in test/
answered here How to test private functions/methods in Flutter?
I'm trying to get the properties of a dynamic Class name (also trying to instantiate it) but the next code doesn't work because I think I need to import the dart file that has the Class code in the file where I want to reflect it:
//I import the file in other Dart file
import 'MyClass.dart'; //This only have a class named MyClass with some properties
import 'OtherClass.dart'
class mainClass {
void mainFunction () {
var properties = OtherClass.getProperties('MyClass');
}
}
Here is the OtherClass contents:
import "dart:mirrors";
class OtherClass {
static getProperties (String className) {
ClassMirror cm = reflectClass(className);
for (var m in cm.declarations.values)
print(MirrorSystem.getName(m.simpleName));
}
}
is there anyway to reflect a class that is not imported in the actual Dart file?
Hope this makes sense, thanks in advance.
You need to find the library containing the class first. Use currentMirrorSystem().libraries to get all libraries imported in your application. If you want to avoid disambiguities, add unique library declarations to your library and pass the library name to getProperties() for exact lookups.
import "dart:mirrors";
class OtherClass {
static getProperties(String className) {
var classSymbol = new Symbol(className);
var libs = currentMirrorSystem().libraries;
var foundLibs = libs.keys.where((lm) =>
libs[lm].declarations.containsKey(classSymbol) &&
libs[lm].declarations[classSymbol] is ClassMirror);
if (foundLibs.length != 1) {
throw 'None or more than one library containing "${className}" class found';
}
ClassMirror cm = libs[foundLibs.first].declarations[classSymbol];
for (var m
in cm.declarations.values) print(MirrorSystem.getName(m.simpleName));
}
}
I tried to dynamically create a new instance of a class like this:
this.componentClass.newInstance(new Symbol(''), [this, el]).reflectee;
The class reflected in this.componentClass is called ButtonComponent and it is a subclass of Component. When running a test on this, I get an error:
Test failed: Caught No constructor 'ButtonComponent.' declared in class 'ButtonComponent'.
NoSuchMethodError : method not found: 'ButtonComponent.'
Receiver: Type: class 'ButtonComponent' Arguments: [...]
There are default constructors in both Component and ButtonComponent classes. Here is the code, to make sure I didn't miss anything:
class Component {
Element element ;
Template template;
Component(this.template, this.element) {
this.element.replaceWith(new Element.html(template.html));
}
}
class ButtonComponent extends Component {
ButtonComponent(template, element) : super(template, element) {};
}
Any ideas what is wrong here? Thank you.
I just made a similar test in 1.0.0.3_r30187 and I don't get this error. If you don't use the last stable version of Dart you should update your version.
Here's my tested code :
import 'dart:html';
import 'dart:mirrors';
class Component {
Element element ;
Component(this.element) {
this.element.children.add(new Element.html("<b>Dart rocks</b>"));
}
}
class ButtonComponent extends Component {
ButtonComponent(element) : super(element);
}
main() {
final a = reflectClass(ButtonComponent).newInstance(new Symbol(''),
[document.documentElement]).reflectee;
print(a); // display : Instance of 'ButtonComponent'
}