Created
December 15, 2010 14:23
-
-
Save JamieMason/741989 to your computer and use it in GitHub Desktop.
Allows you to create a jQuery style (like $('a').attr(), $('a').css()) getter and setter function for any variable or property you choose. When a property name of your subject is provided, it's returned. If a 2nd argument is passed as well, the named prop
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
/** | |
* Allows you to create a jQuery style (like .attr(), .css()) getter and setter function for any variable or property you choose. | |
* When a property name of your subject is provided, it's returned. if a 2nd argument is passed as well, your subject is set to that value | |
* | |
* @param property The variable or property your getter/setter will operate on | |
* @return [chainTo] {Object} Optionally return the object the subject is a property of, to allow chaining | |
* @author https://github.com/JamieMason | |
*/ | |
function createGetterSetter(subject, chainTo) | |
{ | |
return function() | |
{ | |
return (function (name, value) | |
{ | |
// return the property owning object by default, to allow calls to be chained | |
var self = this, | |
returnValue = chainTo; | |
switch (true) | |
{ | |
// Set many: obj.method({name:'value', name:'value'}); | |
case $.isPlainObject(name) : $.extend(self, name); | |
break; | |
// Set one: obj.method('name', 'value'); | |
case arguments.length === 2 : self[name] = value; | |
break; | |
// Get one: obj.method('name'); | |
default : returnValue = self[name]; | |
} | |
return returnValue; | |
}).apply(subject, arguments); | |
}; | |
} |
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
function someConstructor (spec) | |
{ | |
var that = {}, | |
_privateOptions = spec; | |
that.option = createGetterSetter(_privateOptions, that); | |
return that; | |
} | |
var someInstance = someConstructor({ | |
jamie : 'mason' | |
}); | |
someInstance.option('jamie'); | |
// >>> 'mason' | |
someInstance.option('jamie', 'jasta'); | |
// >>> someInstance | |
someInstance.option('jamie'); | |
// >>> 'jasta' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment