Currently, I am faced with integrating a component that would greatly benefit from Dependency Injection (DI) into an existing framework where DI was not considered during its initial design. The configuration defining dependencies is sourced from a backend model, which, is rather basic at this point, containing just a key to determine the availability of a specific view.
To incorporate this dependency using require, the code structure looks something like this:
// Dependency
define(['./otherdependencies'], function(Others) {
return {
dep: "I'm a dependency"
};
});
The injector implementation currently resembles:
// view/injector
define([
'./abackendmodel',
'./dependency'
], function(Model, Dependency) {
return {
show: function() {
if (Model.showDepency) {
var dep = new Dependency();
this.$el.append(dep);
}
}
};
});
The issue arises because additional dependencies required by the component might not be available when it should not be displayed. Therefore, the goal is to only specify and load the dependency if Model.showDependency
is true. While I have come up with a couple of solutions, none seem ideal.
Idea one: Implement another asynchronous require call based on the model attribute. The modified injector code would look like this:
// Idea 2 view/injector
define([
'./abackendmodel'
], function(Model) {
var Dep1 = null;
if (Model.showDepedency) {
require([
'./dependency'
], function(Dependency) {
Dep1 = Dependency;
});
}
return {
show: function() {
if (Dep1) {
var dep = new Dep1();
this.$el.append(dep);
}
}
};
});
However, this approach has its limitations as calling show
before the async require completion will keep Dep1
as null, resulting in errors. Additionally, the conditional check within show
remains a concern.
Idea two:
An experimental concept involving manipulation of require config paths. Although it seems unlikely to work, the idea revolves around having separate configurations for './dependency'
to traverse different locations based on Model.showDependency
. Yet, manipulating the require config at runtime presents challenges.
Idea three:
Possibly the best interim solution involves having the dependency return null based on the Model.showDependency
attribute. Despite lingering conditionals, this method prevents unnecessary initialization code execution.
Seeking insights or alternative suggestions!