Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Created December 15, 2010 14:23
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 JamieMason/741989 to your computer and use it in GitHub Desktop.
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
/**
* 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);
};
}
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