Message from JavaScript discussions

April 2019

— And refer to this.save when it needs to add some data to it or something

— 

You could also instead provide a callback to the game class:

function mySaver(data) {
console.log('saved with:', data);
}

new Game(mySaver);

// and inside Game:

constructor(saver) {
this.saver = saver;
}

addToInventory(item) {
this.inventory.push(item);
this.saver({ inventory: this.inventory });
}

— That way you can pass in a saver that actually saves to file / localStorage / whatever later

— You also probably want some initial / loaded save data to pass to the constructor as well:

constructor(data, saver) {

Message permanent page

— If you want to go the proper "OOP way", you might want a separate class at this point:


class SaveData() {
static load() {
return loadDataSomehow();
}
static save() {
return saveDataSomehow();
}
}

Message permanent page

— Maybe you can make save data take a path of some kind, instead of static methods, then it could be something like:

class SaveData {
constructor(path) {
this.path = path;
}
save(data) {
return fs.writeFileSync(
this.path,
JSON.stringify(data));
}
load(path = this.path) {
return JSON.parse(
fs.readFileSync(path));
}
}

Message permanent page

— And you would instantiate like so:

new Game(new SaveData('data/save.json'));

— Within Game:

constructor(saveData) {
this.saveData = saveData;
}

addToInventory(item) {
this.inventory.push(item);
// the object should probably be replaced by this.getData() or something, which would produce an object containing all data to be saved
this.saveData.save({ inventory: this.inventory });
}

Message permanent page

— And you could save less often if you wished (instead of at every change)

— Suggest a good website project.

— All of this is clearly out of my league TRGWII 😂

— Heh