Last active
August 29, 2015 13:56
-
-
Save rymoore99/9093710 to your computer and use it in GitHub Desktop.
Function for creating a namespace equivalent in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id='result'></div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Util = {}; | |
Util.namespace = (function (root) { | |
var ns_regex = /^([\$\_a-z][\$\_a-z\d]*\.?)+$/i; | |
function genNS(ns) { | |
if (!ns.match(ns_regex)) { | |
return; | |
} | |
// split the namespace by the periods | |
ns = ns.split('.'); | |
var base = root; | |
for (var i = 0; i < ns.length; i++) { | |
// and create a new object for each | |
base[ns[i]] = base[ns[i]] || {}; | |
base = base[ns[i]]; | |
} | |
return base; | |
} | |
return function (ns) { | |
// allow multiple arguments to be passed | |
var args = Array.prototype.slice.call(arguments); | |
var ret = []; | |
while (args.length) { | |
ns = genNS(args.shift()); | |
if (ns) { | |
ret.push(ns); | |
} | |
} | |
if (ret.length == 0) { | |
return; | |
} | |
if (arguments.length == 1) { | |
return ret[0]; | |
} | |
return ret; | |
}; | |
} (this)); | |
// Example of declaring a new namespace using this method | |
Util.namespace('Namespace1.Namespace2'); | |
// also can use the following to define multiple namespaces at once: | |
// namespace('Namespace1.Namespace2', 'Namespace1.Namespace3'); | |
// example class using the new namespace | |
Namespace1.Namespace2.myClass = function($) { | |
function init() { | |
$('#result').text('Namespace worked!'); | |
} | |
return { | |
init:init | |
} | |
}($); | |
// call the init method when the page loads | |
$(function(){ | |
Namespace1.Namespace2.myClass.init(); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: Javascript namespace example | |
authors: | |
- Ryan Moore |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment