Added dependency injection to command handlers.

This commit is contained in:
Borys Levytskyi
2015-04-03 12:05:04 +03:00
parent ce2db72582
commit 51ad680236
3 changed files with 31 additions and 27 deletions

View File

@@ -39,6 +39,17 @@
cmd.subscribe(handler);
}
if (typeof handler == "object") {
if(typeof handler.execute != "function"){
console.warn('Given handler is an object, but doesn\'t have "execute" function');
return cmd;
}
this.di.resolveProperties(handler);
cmd.subscribe(handler.execute.bind(handler));
}
return cmd;
};
@@ -55,8 +66,6 @@
runObservers.forEach(function(o){ o(); });
}
window.app = app;
app.addControllerMixin = function (component) {
component.attachView = function(viewElement) {
@@ -77,5 +86,6 @@
};
}
window.app = app;
})(window.should, window.commandr, window.bindr, window.Container);

View File

@@ -1,7 +1,6 @@
(function(should){
function Container(store) {
this.store = {};
this.resolved = {};
}
Container.prototype.register = function(name, inst) {
@@ -13,10 +12,11 @@
return reg;
};
// TODO: Check for circular - dependencies
Container.prototype.resolve = function(name) {
var reg = this.store[name];
if(reg == null) {
throw new Error(''); // TODO: wrote
throw new Error(name + ' component is not registered');
}
if(reg.resolved == null) {
@@ -34,6 +34,10 @@
if(property[0] == '$') {
var name = property.substr(1, property.length - 1);
instance[property] = this.resolve(name);
if(instance[property] == null) {
console.log('"' + property + '" property couldn\'t be resolved')
}
}
}
};

View File

@@ -36,23 +36,25 @@
(function(){
var app = window.app;
var expression = app.service('expression');
var html = app.service('html');
var resultView = app.service('resultView');
// Expression
app.command('dispatchInput', function(cmdArgs) {
app.command('dispatchInput', {
$expression: null,
$resultView: null,
execute:function(cmdArgs) {
var expr = expression.parse(cmdArgs.input);
if(expr == null) {
return;
var expr = this.$expression.parse(cmdArgs.input);
if(expr == null) {
return;
}
var expressionView = new window.app.views.ExpressionView(expr);
this.$resultView.insert(expressionView.render());
cmdArgs.commandHandled = true;
}
var expressionView = new window.app.views.ExpressionView(expr);
resultView.insert(expressionView.render());
cmdArgs.commandHandled = true;
});
// Help
@@ -93,18 +95,6 @@
cmdArgs.commandHandled = true;
});
app.di.register("ts", {
$html:null,
doStuff: function() {
console.log(this.$html);
}
});
app.di.register('html', { he: 23});
var t = app.di.resolve('ts');
t.doStuff();
app.bootstrap(document.getElementById('rootView'));
})();