Skip to content

Instantly share code, notes, and snippets.

@focusaurus
Created July 19, 2012 01:51
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 focusaurus/3140257 to your computer and use it in GitHub Desktop.
Save focusaurus/3140257 to your computer and use it in GitHub Desktop.
Add named get/set methods to backbone models
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