Skip to content

Instantly share code, notes, and snippets.

@hellatan
Last active August 29, 2015 13:57
Show Gist options
  • Save hellatan/9606542 to your computer and use it in GitHub Desktop.
Save hellatan/9606542 to your computer and use it in GitHub Desktop.
Creates jQuery element selectors
/**
* Creates a new property on an object
* http://jsfiddle.net/hellatan/AQPQ7/
*
* @param {object} obj The object with the property to update/create
* @param {string} [key] The key to check for to create new property
* @param {string} [newKey] The new key to create
* @returns {Object}
*
* @example
* var ret = { ... };
* var els = {
* element1: {
* selector: '.element-1'
* },
* element2: {
* selector: '.element-2'
* },
* uniqueElement1: {
* selector: '#uniqueElement1'
* },
* uniqueElement2: {
* selector: '#uniqueElement2'
* }
* };
* // defaulted arguments in method: key, newKey
* els = createElementSelectors(els);
* ret = $.extend(ret, els);
*/
function createElementSelectors(obj, key, newKey) {
key = key || "selector";
newKey = newKey || "$el";
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
var item = obj[p];
if (item[key]) {
item[newKey] = $(item[key]);
}
}
}
return obj;
}
/**
* Takes the keys from the `selectors`, creates new objects with the values from the keys of the `keyMap`
* and then places them on the `obj`
* http://jsfiddle.net/hellatan/fdq7U/1/
*
* @param {object} obj The object to modify/update
* @param {string} selectors An object where the key will be placed onto the `obj` as an object
* with keys created from the values of the keyMap
* @param {string} [keyMap] An object that has a 'plain' and '$el' as keys that map to new key names
* that will be created inside a new object from `selectors`
* @returns {Object}
*
* @example
* var obj = {
* val1: true,
* val2: true,
* val3: false
* };
* var selectors = {
* element1: '.element-1',
* element2: '.element-2',
* element3: '.element-3',
* val3: '.val-3'
* };
* var keyMap = {
* plain: 'selector',
* $el: '$el'
* };
*
* var ret = createMappedElements(obj, selectors, keyMap);
*
* output:
*
* ret.val1 = true;
* ret.val2 = true;
* ret.val3 = false;
* ret.element1 = {
* selector: '.element-1'
* $el: $('.element-1')
* };
* ret.element2 = {
* selector: '.element-2'
* $el: $('.element-2')
* };
*/
function createElementSelectors(obj, selectors, keyMap) {
keyMap || (keyMap = { plain: 'selector', $el: '$el' });
if (keyMap.plain && keyMap.$el) {
for (var p in selectors) {
// don't overwrite existing properties!
if (selectors.hasOwnProperty(p) && !obj.hasOwnProperty(p)) {
obj[p] = {};
obj[p][keyMap.plain] = selectors[p];
obj[p][keyMap.$el] = $(p);
}
}
}
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment