Skip to content

Instantly share code, notes, and snippets.

@mattjburrows
Created March 4, 2014 20:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattjburrows/9355093 to your computer and use it in GitHub Desktop.
Save mattjburrows/9355093 to your computer and use it in GitHub Desktop.
Require JS module for getting / setting data required in multiple modules
define(function() {
// Set the privately scoped object.
// Its properties are modified via the get / set methods returned from the module.
// We can keep values private by setting the 'private' part to true and set the 'value' part as the property value.
var helper = {
foo: {
'private': true,
'value': 'Private var'
},
classes: {
'active': 'is-active',
'expanded': 'is-expanded'
}
},
getter = function(part) {
// Make sure a part argument has been passed
// Then check to see if it exists on the helper object.
if(part && helper[part]) {
// Then check the the helper[part] to see if it has a private property
// And check to see if that is set to true if it exists.
if(helper[part].hasOwnProperty('private') && true === helper[part]['private']) {
return helper[part]['value'];
}
else {
return helper[part];
}
}
return false;
},
setter = function(part, val) {
// Make sure the arguments have been passed.
if(part && val) {
// Run a check to see if the part exists...
if(helper[part]) {
// Make sure that part isn't private.
if(!helper[part]['private']) {
helper[part] = val;
}
}
// Else set that part.
else {
// Run a check to see if we want to make the part private or not
if(val.hasOwnProperty('private') && true === val['private']) {
helper[part] = {
'private': true,
'value': val['value']
};
}
else {
helper[part] = val;
}
}
// Return the value.
return getter(part);
}
return false;
};
return {
set: setter,
get: getter
};
});
// You can then access the Helper properties via.
define(['helpers'], function(Helper) {
Helper.get('bar');
Helper.set('foo', {
'private': true,
'value': 'Private var'
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment