Last active
August 29, 2015 14:12
-
-
Save nolanlawson/fa42662cdfeeaa7b78fc to your computer and use it in GitHub Desktop.
Live changes with documents included
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<body> | |
<pre id="display"></pre> | |
<script src="//cdn.jsdelivr.net/pouchdb/latest/pouchdb.min.js"></script> | |
<script src="index.js"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Destroy the database before doing anything, because I want | |
// you to see the same thing if you reload. | |
// Ignore the man behind the curtain! | |
new PouchDB('sample').destroy().then(function () { | |
return new PouchDB('sample'); | |
}).then(function (db) { | |
function log(str) { | |
var display = document.getElementById('display'); | |
display.innerHTML = display.innerHTML || ''; | |
display.innerHTML += '\n' + str; | |
} | |
// | |
// IMPORTANT CODE STARTS HERE | |
// | |
db.changes({ | |
since: 'now', | |
include_docs: true, | |
live: true | |
}).on('change', function (change) { | |
log('Change in doc with id "' + change.id + '":'); | |
if (change.deleted) { | |
log(' It was deleted.'); | |
} else { | |
log(' It was added or modified. Current doc is:\n ' + | |
JSON.stringify(change.doc) + '\n'); | |
} | |
}).on('error', function (err) { | |
// handle errors | |
}); | |
db.put({_id: 'myNewDoc'}).then(function () { | |
return db.put({_id: 'myModifiedDoc'}); | |
}).then(function () { | |
return db.get('myModifiedDoc'); | |
}).then(function (doc) { | |
return db.put(doc); // modify | |
}).then(function () { | |
return db.put({_id: 'myDeletedDoc'}); | |
}).then(function () { | |
return db.get('myDeletedDoc'); | |
}).then(function (doc) { | |
return db.remove(doc); | |
}).catch(function (err) { | |
// handle errors | |
}); | |
// | |
// IMPORTANT CODE ENDS HERE | |
// | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment