Skip to content

Instantly share code, notes, and snippets.

@ndelage
Created April 16, 2014 20:14
Show Gist options
  • Save ndelage/10928274 to your computer and use it in GitHub Desktop.
Save ndelage/10928274 to your computer and use it in GitHub Desktop.
Quotes, from plain JS to OOJS
$(document).ready(function() {
$("#quote_body").on('keyup', function() {
var currentCount = $(this).val().length;
$("#count").html(currentCount);
if(currentCount > 20) {
$("#body-length-status").addClass("over-limit");
} else {
$("#body-length-status").removeClass("over-limit");
}
});
$("#new_quote").on('submit', function(e) {
e.preventDefault();
var form = this;
$.post( $(this).attr('action'),
$(this).serialize() ).done(function(r) {
form.reset();
});
});
});
function Quote(body, author) {
this.body = body;
this.author = author;
}
Quote.prototype.MAX_LENGTH = 20;
Quote.prototype.characterCount = function() {
return this.body.length;
}
Quote.prototype.isOverLimit = function() {
return this.characterCount() > this.MAX_LENGTH;
}
Quote.prototype.attributes = function() {
return {"quote[body]": this.body,
"quote[author]": this.author};
}
Quote.prototype.save = function() {
return $.post("/quotes", this.attributes());
}
function QuoteView(el, model) {
this.$el = el;
this.model = model;
this.$el.find("#quote_body").on('keyup', this.updateCharacterCount.bind(this));
this.$el.on('submit', this.saveQuote.bind(this));
}
QuoteView.prototype.updateCharacterCount = function(e) {
this.updateQuote();
var currentCount = this.model.characterCount();
this.$el.find("#count").html(currentCount);
if(this.model.isOverLimit()) {
this.$el.find("#body-length-status").addClass("over-limit");
} else {
this.$el.find("#body-length-status").removeClass("over-limit");
}
}
QuoteView.prototype.updateQuote = function() {
this.model.author = this.$el.find("#quote_author").val();
this.model.body = this.$el.find("#quote_body").val();
}
QuoteView.prototype.saveQuote = function(e) {
e.preventDefault();
this.updateQuote();
// we'll be calling .reset(), which isn't a method
// available on this.$el, but it is a method available
// on the browser DOM object, which is avaible via
// this.$el[0]
var form = this.$el[0];
this.model.save().done(function(resp) {
form.reset();
});
}
$(document).ready(function() {
var quote = new Quote($("#quote_body").val(),
$("#quote_author").val());
var quoteView = new QuoteView($("#new_quote"), quote);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment