我设法从一个课程中重新创建了MVC卡路里跟踪器应用程序,现在我正尝试将其转换为ES6类。
我有点不理解如何在Controller内部调用Module中的方法以返回我需要的项目。
class Item {
constructor() {
this.data = {
items: [{
name: 'Salad',
calories: 200,
id: 0
},
{
name: 'Eggs',
calories: 500,
id: 1
}],
totalCalories: 0,
currentItem: null
}
};
getItems() {
return this.data.items
};
logData = () => {
console.log(data.items);
};
}
class App {
constructor(Item, UI) {
this.Item = Item;
this.UI = UI;
}
init() {
const items = Item.getItems();
UI.populateItemList(items)
}
}
const application = new App(new Item(), new UI())
当我尝试在控制台中调用Item.logData()
时,它给了我TypeError:this.data is undefined。我在网上进行了研究,看来我声明的方法仅适用于构造函数。我将如何声明将在Controller或任何其他类中使用的方法,就像我在下面通过从构造函数中返回一个方法一样进行声明?
我最初尝试转换的内容如下:
const ItemCtrl = (function () {
const Item = function (id, name, calories) {
this.name = name;
this.id = id;
this.calories = calories;
}
const data = {
items: StorageCtrl.getStorage(),
totalCalories: 0,
currentItem: null
}
return {
getItems: function () {
return data.items
},
logData: function () {
return data;
}
}
const App = (function (ItemCtrl, StorageCtrl, UICtrl) {
return {
init: function () {
const items = ItemCtrl.getItems();
UICtrl.populateItems(items);
}
}
})(ItemCtrl, StorageCtrl, UICtrl);
App.init();
您需要首先初始化控制器:
class App {
constructor(Item, UI) {
this.item = new Item();
this.UI = new UI();
}
init() {
const items = this.item.getItems();
this.UI.populateItemList(items)
}
}