Created
July 19, 2012 01:51
-
-
Save focusaurus/3140257 to your computer and use it in GitHub Desktop.
Add named get/set methods to backbone models
This file contains hidden or 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
addConvenienceMethods = -> | |
for prop, value of this.attributes | |
((prop) -> | |
#Define a setter/getter function | |
this[prop] = (newValue...) -> | |
if newValue.length | |
this.set prop, newValue[0] | |
return this | |
else | |
return this.get prop | |
#Use the newly-defined setter function to store the default value | |
this[prop](value) | |
).call(this, prop) | |
########## Base Model Superclass ########## | |
class exports.Model extends Backbone.Model | |
initialize: -> | |
addConvenienceMethods.call this | |
idAttribute: '_id' #This provides MongoDB compatibility | |
#Change the backbone validate API, which I dislike | |
validate: => | |
errorInfo = new api.ErrorInfo() | |
foundErrors = false | |
for prop, value of this.attributes | |
if this[prop] and typeof(this[prop].validate) == 'function' | |
message = this[prop].validate value | |
if message | |
foundErrors = true | |
errorInfo.errors[prop] = message | |
if foundErrors | |
return errorInfo | |
else | |
return false | |
_performValidation: => | |
#Disable validation during calls to 'set' | |
return true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment