public
Last active

Micro JavaScript Dependancy Injection. Written in CoffeeScript and for the haters - converted and cleaned into JS. This is *approximately* how AngularJS works.

  • Download Gist
di.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
# Micro JavaScript Dependancy Injection
 
define = (name, val) ->
#init modules map if missing
define.mods = define.mods or {}
#store 'name'
define.mods[name] = val
 
inject = (fn) ->
#regex match on function.toString()
m = fn.toString().match /function\s(\w+)?\((.*)\)/
throw "Function parse failed" unless m
#prepare arguments
args = []
#loop through function parameter names
for name in m[2].split(", ")
continue unless name
#look for module with 'name'
m = define.mods[name]
throw "Missing '#{name}' module" unless m
#add to arguments
args.push m
#call function with arguments
fn.apply this, args
 
#example usage
 
define 'a', 42
define 'b', 21
define 'c', 7
 
inject -> print "no-args" #no-args
inject (b) -> print b #21
inject (a,b,c) -> print a+b-c #56
di.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
// Micro JavaScript Dependancy Injection
 
var define = function(name, val) {
//init modules map if missing
define.mods = define.mods || {};
//store 'name'
return define.mods[name] = val;
};
 
var inject = function(fn) {
var args, m, name, i, params;
//regex match on function.toString()
m = fn.toString().match(/function\s(\w+)?\((.*)\)/);
if (!m) throw "Function parse failed";
//prepare arguments
args = [];
params = m[2].split(", ");
//loop through function parameter names
for (i = 0; i < params.length; i++) {
name = params[i];
if (!name)continue;
//look for module with 'name'
m = define.mods[name];
if (!m) throw "Missing '" + name + "' module";
//add to arguments
args.push(m);
}
//call function with arguments
return fn.apply(this, args);
};
 
//example usage
define('a', 42);
define('b', 21);
define('c', 7);
 
inject(function() {
return print("no-args");
});
 
inject(function(b) {
return print(b); //21
});
 
inject(function(a, b, c) {
return print(a + b - c); //56
});

As Function.toString() is defined lexically (and so statically), I think it would be nice also to have such thing implemented as a source code transform.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.