Hasan A Yousef Hasan A Yousef - 4 months ago 16
Dart Question

Dartlang class VS JavaScript class

I've the below JS code using JS classes, that multiple rectangles got generated, in different random locations,
the static rectangle start moving upon click, and the moving rectangle is destroyed if clicked.

I want to re-write the same code in Dart language, I did not know what shall I use instead of the JS

myRect.prototype
in dart, considering that I prefer not to include all the class properties and functions inside the main
class { }
any idea?


var NS="http://www.w3.org/2000/svg";
var SVG=function(h,w){
var svg=document.createElementNS(NS,"svg");
svg.width=w;
svg.height=h;
return svg;
}
var svg=SVG(1200,1500);
document.body.appendChild(svg);

class myRect {
constructor(x,y,h,w,fill,name) {
this.name=name;
this.SVGObj= document.createElementNS(NS,"rect");
self = this.SVGObj;
self.x.baseVal.value=x;
self.y.baseVal.value=y;
self.width.baseVal.value=w;
self.height.baseVal.value=h;
self.style.fill=fill;
self.addEventListener("click",this,false);
}
}

Object.defineProperty(myRect.prototype, "draw", {
get: function() {
return this.SVGObj;
}
});

myRect.prototype.handleEvent= function(evt){
self = this.SVGObj;
switch (evt.type){
case "click":
if (typeof self.moving == 'undefined' || self.moving == false) self.moving = true;
else self.moving = false;

if(self.moving == true)
self.move = setInterval(()=>this.animate(),100);
else{
clearInterval(self.move);
self.parentNode.removeChild(self);
}
break;
default:
break;
}
}

myRect.prototype.step = function(x,y) {
return svg.createSVGTransformFromMatrix(svg.createSVGMatrix().translate(x,y));
}

myRect.prototype.animate = function() {
self = this.SVGObj;
self.transform.baseVal.appendItem(this.step(1,1));
};

for (var i = 0; i < 100; i++) {
var x = Math.random() * 500,
y = Math.random() * 300;

var r= new myRect(x,y,10,10,'#'+Math.round(0xffffff * Math.random()).toString(16),'this is my name');
svg.appendChild(r.draw);
}

Answer

You can't add methods to a class or object dynamically in Dart. Your options are:

  1. Put them inside the class
  2. Make them functions that take the rectangle as an argument

I would go with (2), just make them functions that accept an instance of your class:

handleEvent(myRect, evt){
  // ...
}