Last active
December 18, 2015 23:49
-
-
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.
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
// 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(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The above gist accompanies this blog post: http://blog.founddrama.net/2013/06/on-protocols/
Also: in the gist:
_
is for Underscore$
is for jQuery(Just so we're all clear about our assumptions.)