Last active
January 2, 2016 17:49
-
-
Save ajhekman/8339317 to your computer and use it in GitHub Desktop.
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
| angular.module('app') | |
| .factory "PropertyModel", ($log) -> | |
| class PropertyModel | |
| @defaults: -> | |
| angular.copy( {} ) | |
| constructor: (properties)-> | |
| @update(properties) | |
| accessors: {} | |
| # Pass in string of property name | |
| # returns property value | |
| get: (propName) -> | |
| @_getOrCallProperty propName | |
| # Pass in string of property name and value, or if complex property; values | |
| set: (propName, values...) -> | |
| setterMethod = @accessors["set_#{propName}"] | |
| if setterMethod? | |
| setterMethod.apply @, values | |
| else | |
| if values.length > 1 then throw "Cannot provide multiple values for a singular property" | |
| @properties[propName] = values[0] | |
| # Pass in an object of key/value pairs to use as properties. | |
| # This will reset the properties of this object to those passed in | |
| # plus any default properties defined on the constructing class. | |
| update: (properties={}) -> | |
| unless angular.isObject properties then throw "'#{@.constructor?.name}' properties must be contructed with an object '{}'" | |
| @properties = @properties || {} | |
| unless _.isEqual(angular.copy(@properties), properties) | |
| defaults = this.constructor.defaults?() || {} | |
| @properties = _.extend(defaults, properties) | |
| _getOrCallProperty: (propName) -> | |
| readerMethod = @accessors?["get_#{propName}"] | |
| if readerMethod? | |
| readerMethod.apply @ | |
| else if @properties.hasOwnProperty(propName) | |
| @properties[propName] | |
| else | |
| $log.error "PropertyNotFound: '#{propName}' on #{@.constructor?.name} Model" | |
| return null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment