<!-- Include dexie.js -->
<script src="https://npmcdn.com/dexie/dist/dexie.js"></script>
<script src="https://npmcdn.com/typeson/dist/typeson.js"></script>
<!-- Some HTML for the log window -->
<a href="http://dexie.org/docs/API-Reference" target="_new">Dexie API Reference (new tab)</a>
<h3>Log</h3>
<textarea id="log"></textarea>
<!-- Just a simple log function... -->
<script>
function log(txt) {document.getElementById('log').value+=txt+"\n";}
</script>
CSS
textarea#log
{
width: 100%;
height: 1000px;
}
JavaScript
//
// Custom classes
//
class Friend {
constructor (name, age, cars) {
this.name = name;
this.age = age;
this.cars = cars;
}
sayHello() {
log("Hi, I am " + this.name + ", " + this.age + "!");
}
listCars() {
return this.cars.map(car => car.brandAndModel());
}
}
class Car {
constructor (brand, model) {
this.brand = brand,
this.model = model;
}
brandAndModel() {
return this.brand + " " + this.model;
}
}
// Configure typeson
var TSON = new Typeson().register({
Friend,
Car
});
//
// Define database
//
var db = new Dexie("MyTypesonDB");
db.version(1).stores({
friends: '++id,name,age'
});
log ("Using Dexie v" + Dexie.semVer);
//
// Query Database
//
db.open().then(() => {
const car = new Car("Volvo", "v70");
const friend = new Friend("Foo", 42, [car]);
return db.friends.add(TSON.encapsulate(friend));
}).then(() => {
return db.friends
.where('age')
.between(30,45)
.toArray();
}).then(friends => {
return friends.map(TSON.revive);
}).then(friends => {
log("Testing if a friend can say hello...");
friends[0].sayHello();
log("Testing if we can list cars for a friend...");
const cars = friends[0].listCars();
log("Got car list: " + cars);
}).then(function(){
return db.delete(); // So you can experiment again and again...
}).catch (Dexie.MissingAPIError, function (e) {
log ("Couldn't find indexedDB API");
}).catch ('SecurityError', function(e) {
log ("SeurityError - This browser doesn't like fiddling with indexedDB.");
log ("Go run some samples instead at: https://github.com/dfahlander/Dexie.js/wiki/Samples");
}).catch (function (e) {
log (e);
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.