Skip to content

Instantly share code, notes, and snippets.

@founddrama
Last active December 18, 2015 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save founddrama/5864341 to your computer and use it in GitHub Desktop.
Save founddrama/5864341 to your computer and use it in GitHub Desktop.
Gist accompanies a blog post which is a follow-up to my follow-up write-up of my 6/19/2013 BurlingtonJS talk.
// Where `reviews` is a list of Review objects...
// shared by client and server: simple naive validator:
var ValidationProtocol = (function() {
var validationRules = {
// properties to validate + functions...
};
return {
// using our imagination here:
isValid: function() {
var valid = true;
for (var p in this) {
if (validationRules[p]) {
valid = validationRules[p](this[p]);
}
if (!valid) break;
}
return valid;
}
};
}());
// on the server
var ServerPersistenceProtocol = {
// assuming a mongodb connection through Mongoose or similar:
update: function() {
if (this.isValid()) {
this.save(function(err) {
if (err) console.error('[mongo] ERROR: %s', err.message);
else console.log('[mongo] OK!');
});
}
return this;
}
};
_.extend(Review.prototype,
ServerPersistenceProtocol,
ValidationProtocol);
_.each(reviews, function(r) {
r.update();
});
// on the client
var ClientPersistenceProtocol = {
// using our imagination here:
update: function() {
var _updates = this.getUpdates();
if (!_.isEmpty(_updates) && this.isValid()) {
$.ajax('/reviews', { type: 'PUT', data: _updates });
}
return this;
}
};
_.extend(Review.prototype,
ClientPersistenceProtocol,
ValidationProtocol);
_.each(reviews, function(r) {
r.update();
});
@founddrama
Copy link
Author

The above gist accompanies this blog post: http://blog.founddrama.net/2013/06/on-protocols/

Also: in the gist:

(Just so we're all clear about our assumptions.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment