Created
October 31, 2012 16:38
-
-
Save francescoagati/3988143 to your computer and use it in GitHub Desktop.
simple Dependency injection in livescript
This file contains hidden or 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 Container, cnt; | |
Container = (function(){ | |
Container.displayName = 'Container'; | |
var prototype = Container.prototype, constructor = Container; | |
function Container(){ | |
var ref$; | |
ref$ = [{}, {}], this.registry = ref$[0], this.shared = ref$[1]; | |
} | |
prototype.set = function(name, opt, fn){ | |
var registry; | |
opt == null && (opt = {}); | |
registry = (function(){ | |
switch (false) { | |
case opt['shared'] !== true: | |
return this.shared; | |
default: | |
return this.registry; | |
} | |
}.call(this)); | |
return registry[name] = { | |
blk: fn | |
}; | |
}; | |
prototype.get = function(name){ | |
switch (false) { | |
case this.registry[name] == null: | |
return this.registry[name]['blk'](this); | |
default: | |
return (function(srv){ | |
if (typeof srv['blk'] === 'function') { | |
srv['blk'] = this.shared[name]['blk'](this); | |
} | |
return srv['blk']; | |
}.call(this, this.shared[name])); | |
} | |
}; | |
return Container; | |
}()); | |
cnt = new Container; | |
cnt.set("name", null, function(cont){ | |
return "mario"; | |
}); | |
cnt.set("surname", null, function(cont){ | |
return "rossi"; | |
}); | |
cnt.set("label", null, function(cont){ | |
return cont.get('name') + " " + cont.get('surname'); | |
}); | |
console.log(cnt.get('label')); |
This file contains hidden or 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
class Container | |
-> [@registry,@shared] = [{},{}] | |
set: (name,opt={},fn) -> | |
registry = switch | |
| opt[\shared] == true => @shared | |
| otherwise => @registry | |
registry[name] = {blk:fn} | |
get: (name) -> | |
| @registry[name]? => @registry[name][\blk](@) | |
| otherwise => | |
let srv = @shared[name] | |
srv[\blk] = @shared[name][\blk](@) if typeof srv[\blk] is \function | |
srv[\blk] | |
cnt= new Container | |
cnt.set "name", null, (cont) -> "mario" | |
cnt.set "surname", null, (cont) -> "rossi" | |
cnt.set "label",null, (cont) -> "#{cont.get(\name)} #{cont.get(\surname)}" | |
console.log cnt.get \label | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is awesome. Thank you very much.
Do you think it's worth attempting to create a directory of these kinds of snippets somewhere?