Skip to content

Instantly share code, notes, and snippets.

@saighost
Last active August 29, 2015 14:27
Show Gist options
  • Save saighost/238df340fc28f11cbbda to your computer and use it in GitHub Desktop.
Save saighost/238df340fc28f11cbbda to your computer and use it in GitHub Desktop.
var Objectifier = (function() {
// Utility method to get and set objects that may or may not exist
var objectifier = function(splits, create, context) {
var result = context || window;
for(var i = 0, s; result && (s = splits[i]); i++) {
result = (s in result ? result[s] : (create ? result[s] = {} : undefined));
}
return result;
};
return {
// Creates an object if it doesn't already exist
set: function(name, value, context) {
var splits = name.split('.'), s = splits.pop(), result = objectifier(splits, true, context);
return result && s ? (result[s] = value) : undefined;
},
get: function(name, create, context) {
return objectifier(name.split('.'), create, context);
},
exists: function(name, context) {
return this.get(name, false, context) !== undefined;
}
};
})();
// Creates my.namespace.MyClass
Objectifier.set('my.namespace.MyClass', {
name: 'David'
});
// my.namespace.MyClass.name = 'David'
// Creates some.existing.objecto.my.namespace.MyClass
Objectifier.set('my.namespace.MyClass', {
name: 'David'
}, some.existing.objecto); // Has to be an existing object
// Get an object
Objectifier.get('my.namespace.MyClassToo');
// Try to find an object, create it if it doesn't exist
Objectifier.get('my.namespace.MyClassThree', true);
// Check for existence
Objectifier.exists('my.namespace.MyClassToo'); // returns TRUE or FALSE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment