Model persistence - localStorage example
by Rafał Mikołajun
HTML
<script src="https://rawgit.com/eu81273/jsfiddle-console/master/console.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/5.11.0/jsoneditor.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/5.11.0/jsoneditor.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/object-model.umd.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/bundle/model-persistence.js"></script>
<div id="jsoneditor" style="width: 400px; height: 600px;"></div>
JavaScript
class F1Driver extends modelPersist.Model({
slug: String,
firstName: String,
lastName: String,
teamName: String,
countryCode: String
}) {
get card() {
return `${this.firstName} ${this.lastName} (${this.countryCode}) - ${this.teamName}`;
}
}
class F1DriverLocator extends modelPersist.LocalStorageLocatorAbstract {
get basePath() {
return '/f1-driver';
}
getIdPropName() {
// default is 'id'
return 'slug';
}
}
const editor = new JSONEditor(document.getElementById('jsoneditor'), {mode: 'view'});
const manager = modelPersist.storageFactory.createManager(new F1DriverLocator());
manager.saveSync(new F1Driver({
slug: 'robert-kubica',
firstName: 'Robert',
lastName: 'Kubica',
teamName: 'Williams',
countryCode: 'PL'
}));
manager.saveSync(new F1Driver({
slug: 'fernando-alonso',
firstName: 'Fernando',
lastName: 'Alonso',
teamName: 'McLaren',
countryCode: 'ES'
}));
editor.set(manager.getAll(F1Driver));