I have been trying to wrap my head around all the new options in ECMAscript 6 and to do this I tried to develop a simple setup which would allow me to place absolutely positioned <div>
s on the page.
main.js:
import {Screen} from './objects/screen';
import {Position} from './objects/position';
var welcomeScreen = new Screen("Hello World");
welcomeScreen.title = "Hello World2";
welcomeScreen.position = new Position(100,100);
//Make sure the following does work if you have any advices, because there is a simple mistake which breaks this:
console.log(welcomeScreen.position.x);
var secondScreen = new Screen("Second screen", new Position(200,200));
objects/baseobject.js:
export class BaseObject{
on(eventname,func){
if(typeof this.listeners == "undefined"){
this.listeners = {};
}
if(typeof this.listeners[eventname] == "undefined"){
this.listeners[eventname] = [];
}
this.listeners[eventname].push(func);
return this;
}
trigger(eventname){
if(this.listeners && this.listeners[eventname]){
for(let func of this.listeners[eventname]){
func.call(this);
}
}
}
}
objects/screen.js:
import {BaseObject} from './baseobject';
// private properties:
var pp = {
position: Symbol(),
title: Symbol()
};
export class Screen extends BaseObject{
constructor(title,position = new Position(0,0)){
this.element = document.createElement("div");
this.element.classList.add("screen");
this.title = title;
this.position = position;
document.body.appendChild(this.element);
}
reposition(){
this.element.style.left = this.position.x + "px";
this.element.style.top = this.position.y + "px";
}
set position(position){
var that = this;
this[pp.position] = position;
this[pp.position].on("positionchange",function(){
that.reposition();
}).trigger("positionchange");
}
get position(){
return this[pp.position];
}
set title(value){
this[pp.title] = value;
this.element.textContent = value;
}
get title(){
return this[pp.title];
}
}
objects/position.js:
import {BaseObject} from './baseobject';
// private properties:
var pp = {
x: Symbol(),
y: Symbol()
};
export class Position extends BaseObject{
constructor(x,y){
this[pp.x]=x;
this[pp.y]=y;
}
set x(value){
this[pp.x]=x;
super.trigger("positionchange");
}
get x(){
return this[pp.x];
}
set y(value){
this[pp.y]=y;
super.trigger("positionchange");
}
get y(){
return this[pp.y];
}
}
You can transpile ES6 to ES3 (I think it is 3) using (Google) Traceur.
Points of interest:
- Are there nice ES6 language features I am forgetting?
- Is there a nicer way to handle the 'set triggers' (
->
private property construction)? - Should I be using modules? Combine classes into the same files? etc.
new Name()
stuff which I can't figure out. \$\endgroup\$