Skip to content

Instantly share code, notes, and snippets.

@hoatle
Created February 24, 2012 05:00
Show Gist options
  • Save hoatle/1897890 to your computer and use it in GitHub Desktop.
Save hoatle/1897890 to your computer and use it in GitHub Desktop.
eXo.provide(namespace, obj);
(function(w) {
w.eXo = w.eXo || {};
/**
* Exposes a function to attach its to a namespace, this is similar but more advanced than goog.provide(namespace)
*
* @param namespace the name space string, for example: "eXo.social.MyClass".
* @param obj the associated function or singleton object to be associated with this name space
*/
eXo.provide = function(namespace, obj) {
if (!namespace || !obj) {
if (console) {
console.warn('eXo.provide: namespace or obj is not valid.');
console.info('namespace: ' + namespace);
console.info('obj: ' + obj);
}
return;
}
var names = namespace.split('.');
var tempNamespace = window;
for (var i = 0, len = names.length; i < len; i++) {
if (i == (len - 1)) {
//the last one
tempNamespace[names[i]] = obj;
} else {
tempNamespace = tempNamespace[names[i]] = tempNamespace[names[i]] || {};
}
}
}
})(window);
//sample with Class
(function(eXo) {
var MyClass = function() {
};
MyClass.prototype.sayHi = function() {
alert('Hi!');
};
//exposes
eXo.provide('net.hoatle.MyClass', MyClass);
//Without eXo#provide
/*
window.net = window.net || {};
window.net.hoatle = window.net.hoatle || {};
window.net.hoatle.MyClass = MyClass;
*/
})(eXo);
var myClass = new net.hoatle.MyClass();
myClass.sayHi();
//sample with Singleton Object
(function(eXo) {
var MyObject = {
sayHi: function() {
alert('Hi!');
}
};
eXo.provide("net.hoatle.MyObject", MyObject);
})(eXo || window);
net.hoatle.MyObject.sayHi();
// sample with a root namespace
eXo.provide("hoatlevan", {
sayHi: function() {
alert('Hi!');
}
});
hoatlevan.sayHi();
//exception cases => log and return
eXo.provide(null, {});
eXo.provide('abc', null);
eXo.provide(null, null);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment