Skip to content

Instantly share code, notes, and snippets.

@francescoagati
Created October 31, 2012 16:38
Show Gist options
  • Save francescoagati/3988143 to your computer and use it in GitHub Desktop.
Save francescoagati/3988143 to your computer and use it in GitHub Desktop.
simple Dependency injection in livescript
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'));
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
@525c1e21-bd67-4735-ac99-b4b0e5262290

This is awesome. Thank you very much.

Do you think it's worth attempting to create a directory of these kinds of snippets somewhere?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment