Skip to content

Instantly share code, notes, and snippets.

@jchris
Created April 27, 2011 16:54
Show Gist options
  • Save jchris/944652 to your computer and use it in GitHub Desktop.
Save jchris/944652 to your computer and use it in GitHub Desktop.
jQuery CouchDB Hello World - to use this script, create the map view in futon and click Save As, then upload index.html as an attachment to _design document created with the view. browse to index.html to run the app.
<!DOCTYPE html>
<html>
<head><title>Tiny CouchApp</title></head>
<body>
<h1>Tiny CouchApp</h1>
<form id="new_message">
<label for="message">Message:</label>
<input type="text" name="message" value="">
<p><input type="submit" value="Save &rarr;"></p>
</form>
<ul id="messages"></ul>
</body>
<script src="/_utils/script/jquery.js"></script>
<script src="/_utils/script/jquery.couch.js"></script>
<script>
$(function() {
// make sure this matches the name of your database
var db = $.couch.db("mydb");
$("#new_message").submit(function() {
// save the message to couchdb
var doc = {}, input = $("input[name=message]", this);
doc.message = input.val();
doc.created_at = new Date();
db.saveDoc(doc, {
success : function(r) {
input.val("");
}
});
return false;
});
function redrawMessages() {
// make sure this matches the name of your map view
db.view("messages/by_time", {
descending : true,
success : function(resp) {
var list = $("#messages");
list.empty();
resp.rows.forEach(function(row) {
list.append($('<li/>').text(row.value));
});
}
})
};
redrawMessages();
var changeHandler = db.changes();
changeHandler.onChange(redrawMessages);
});
</script>
</html>
function(doc) {
if (doc.created_at && doc.message) {
emit(doc.created_at, doc.message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment