<script src="https://unpkg.com/[email protected]/lib/injector.js"></script>
<h1>Simple example using Dependency Injection with Diogenes library from CDN</h1>
JavaScript
let injector = new Diogenes();
/*
Declare a constructor function as normal. Dependencies will be passed in in the options object.
*/
class Foo {
constructor(options) {
this.bar = options.bar;
}
getBar() {
console.log(this.bar.name);
}
}
/*
Declare the dependencies that will be passed to the constructor function using service provider keys
*/
Foo.inject = ['bar'];
/* Create the dependent types, again, as normal constructors */
class Bar {
constructor() {
this.name = 'I am Bar';
}
}
/* register all the service providers with the injector
The first argument is the service provider key
The second argument is the service provider, here the constructor function,
The third argument is a constant that defines what kind of object we want
the injector to create. Here we tell the injector to treat the service provider as a constructor function.
*/
injector.register('foo', Foo, Diogenes.INSTANCE);
injector.register('bar', Bar, Diogenes.INSTANCE);
/*
Get an instance of foo from the injector
*/
let foo = injector.get('foo');
// now use it
foo.getBar(); // logs 'I am Bar' to console
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.