Reputation: 3664
Read the example below*, but don't pay too much attention to the EventEmitter
inheritance, please – it just shows the utility of the class
syntax.
I realize that the example is not correct ES2015, since there no such thing as a static class
statement.
What would be the most syntactically lean way to make something like this work in ES2015?
class App extends EventEmitter {
addPage(name) {
this[name] = new App.Page;
this.emit("page-added");
}
static class Page extends EventEmitter {
constructor() {
super();
this._paragraphs = [];
}
addParagraph(text) {
this._paragraphs.push(text);
this.emit("paragraph-added");
}
}
}
Should I just split it up and use a class expression, like below? Seems less elegant.
class App extends EventEmitter {
addPage(name) {
this[name] = new App.Page;
this.emit("page-added");
}
}
App.Page = class extends EventEmitter {
constructor() {
super();
this._paragraphs = [];
}
addParagraph(text) {
this._paragraphs.push(text);
this.emit("paragraph-added");
}
};
Upvotes: 2
Views: 395
Reputation: 664766
Should I just split it up and use a class expression?
Yes, that's the way to go. If you insist on using a declaration, you'd have to make a App.Page = Page
assignment afterwards.
Upvotes: 1
Reputation: 46341
You could have your class created inside addPage
. It will create the "abstraction" I suppose you're looking for, but you'll pay in performance (each addPage
call will be slower.
'use strict';
class EventEmitter {
emit(s) {
alert(s);
}
}
class App extends EventEmitter {
addPage(name) {
class Page extends EventEmitter {
constructor() {
super();
this._paragraphs = [];
}
addParagraph(text) {
this._paragraphs.push(text);
this.emit("paragraph-added");
}
}
this[name] = new Page;
this.emit("page-added");
}
}
var app = new App;
app.addPage("myPage");
app.myPage.addParagraph("Some content");
Alternatively, have both classes defined in a module, and only export the App
class thus preventing pollution of the global scope.
Upvotes: 0