NODEJS(17)Platform - DI
1. DI Introduction
a. Some
consumer, this is the thing that has dependencies
b. Some
dependencies. These are the things that the consumer needs in order to work.
c. Some
Injector. The injector is the thing that connects the consumer to its dependencies.
Take a look at this Examples
var config = require(‘../config.json’);
var User = require(‘./models/user’);
var Group = require(‘./models/group’);
var Post = require(‘./models/post’);
var Client = require(‘./lib/client’);
var client = Client(config);
var user = User(client);
var group = Group(client);
var post = Post(client);
In this example, the
consumers are our models
The dependency is our client.
The injector is the part where we manually require everything and pass the configured parts along.
Dependency Injection Framework
The framework which i.TV wrote is Dependable.
var container = require(‘dependable’).container;
var User = require(‘./models/user’);
var Group = require(‘./models/group’);
var Post = require(‘./models/post’);
var Client = require(‘./lib/client’);
container.register(‘config’, require(‘../config.json’));
container.register(‘client’, function(config) {
return Client(config);
});
container.register(‘user’,User);
container.register(‘group’,Group);
container.register(‘post’, Post);
container.resolve(function(user, group, post) {
});
2. Read the Source codes in Dependable
>
git clone
https://github.com/idottv/dependable.git
>
sudo npm install -g coffee-script
>
coffee --compile index.coffee
3. Some Basic Tips
Array.prototype.slice.call
Array [Object]
prototype [property]
slice [Function] Something like substring for string, slice for array
call [Function]
Array.prototype.slice.call == [].slice
Array.prototype.slice.call(obj, begin, end) = Array.slice(begin, end)
Array.prototype.every()
arr.every(callback[, thisArg])
function isBigEnough(element, index, array){
return (element >= 10);
}
var passed = [12,5,8,130,44].every(isBigEnough);
//false
passed = [12,54,18,130,44].every(isBigEnough);
//true
Function.prototype.apply()
fun.apply(thisArg, [argsArray])
ObjectA.apply(this, arguments); —————> ObjectA.call(this);
apply can extends other object, inherit their methods and properties.
Example to Extends
function Person(name, age){
this.name=name;
this.age=age;
}
function Student(name,age,grade){
Person.apply(this,arguments);
this.grade=grade;
}
var student = new Student(“zhangsan”,21,”grade 1”);
alert(“name:”+student.name+”\n”+”age:”+student.age+”\n”+”grade:”+student.grade);
———>
Person.call(this,name,age);
4. I Plan to Take Reference and Write a DI
I just use hashmap to store the servers I created right now.
References:
Open Source DI
Blogs
angularjs DI