我需要重构ES6中的生活。在ES6中,let和const有一个块作用域,所以我真的需要在ES6中生活吗?这是代码的ES5版本:
var oojs = (function(oojs) {
var createToolbarItems = function(itemElements) {
var items = [];
[].forEach.call(itemElements,
function(el, index, array) {
var item = {
toggleActiveState: function() {
this.activated = !this.activated;
}
};
Object.defineProperties(item, {
el: {
value: el
},
enabled: {
get: function() {
return !this.el.classList.contains('disabled');
},
set: function(value) {
if (value) {
this.el.classList.remove('disabled');
} else {
this.el.classList.add('disabled');
}
}
},
activated: {
get: function() {
return this.el.classList.contains('active');
},
set: function(value) {
if (value) {
this.el.classList.add('active');
} else {
this.el.classList.remove('active');
}
}
}
});
items.push(item);
});
return items;
};
oojs.createToolbar = function(elementId) {
var element = document.getElementById(elementId);
var items = element.querySelectorAll('.toolbar-item');
return {
items: createToolbarItems(items)
}
};
return oojs;
}(oojs || {}));
在ES6中翻译这段代码的最佳方式是什么?我尝试了许多解决方案,但我错过了一些东西,并且我得到了一个错误:oojs is not defined。
也许我可以使用一个类来代替?正如您从代码中看到的,我正在以一种面向对象的方式编写一个Toolbar API (我认为...)
谢谢你的帮助
编辑:多亏了georg,我尝试使用类重构我的代码。这是新的ES6版本:
class Toolbar {
constructor(elementId) {
this.elementId = elementId;
}
get items() {
const element = document.getElementById(this.elementId);
return element.querySelectorAll(".toolbar-item");
}
createToolbarItems() {
return [...this.items].map(el => new ToolbarItem(el));
}
}
class ToolbarItem {
constructor(el) {
this.el = el;
}
get enabled() {
return !this.el.classList.contains('disabled');
}
set enabled(value) {
if (value) {
this.el.classList.remove('disabled');
} else {
this.el.classList.add('disabled');
}
}
get activated() {
return this.el.classList.contains('active');
}
set activated(value) {
if (value) {
this.el.classList.add('active');
} else {
this.el.classList.remove('active');
}
}
toggleActiveState() {
this.activated = !this.activated;
}
}
// const toolbar = new Toolbar('myToolbar');
// const toolbarItems = toolbar.createToolbarItems();
编辑:请检查这段代码的编写方式是否正确,我对ES6还很陌生
再次感谢
发布于 2018-02-27 22:37:47
您可以从分解工具栏项代码(var item及以下版本)开始:
class ToolbarItem
{
constructor(element) {
....
}
}现在,决定是保留enabled和activated作为属性,还是将它们重构为像isEnabled和setEnabled这样的显式方法。在前一种情况下,
class ToolbarItem {
get enabled() {
...
}
set enabled(value) {
...
}
}而普通的方法可以这样定义:
class ToolbarItem {
isEnabled() {
...
}
setEnabled(value) {
...
}
}解决这个问题后,将项目初始化代码替换为items.push(new ToolbarItem(el))和test。
希望这篇文章能帮助你入门,祝你好运!
https://stackoverflow.com/questions/49010953
复制相似问题