学习网易的bearcat

bearcat是网易的一个ioc容器,下面是学习的示例代码:

代码文件构成:




context.json:

{
  "name": "zjw-lib",
  "scan": "lib"
}

scan:表示扫描lib文件夹中的所有文件


lib1.js:

/**
 * Created by Administrator on 2016/5/3.
 */
var BearCat = require('bearcat');
var EventEmitter = require('events').EventEmitter;
var Util = require('util');


var person = function (name, age) {
    EventEmitter.call(this);

    this.human = null;
    this.name = name;
    this.age = age;
    this.lastName = null;
    this.a = null;
};
Util.inherits(person, EventEmitter);


person.prototype.init = function () {
    this.lastName = "zheng";
};

person.prototype.toString = function () {
    return this.name + " " + this.age + " " + this.lastName + " " + this.a+" "+this.human.getName();
};

module.exports = {
    id: "person",
    func: person,
    init: "init",
    scope: "prototype",
    "args": [
        {name: "name", type: "String"},
        {name: "age", type: "Number"}
    ],
    "props": [
        {name: "a", value: 1222},
        {name: "human", ref: "human"}
    ]
};


导出说明:

id:bearcat内部识别的唯一key

func:对象

init:自动执行函数,bearcat调用getBean会自动执行该函数

scope:用于生成对象,默认是singleton(单例模式),每次调用返回old对象

多例(prototype)意味着每次对名叫id的bean的请求, 容器都会创建一个新的bean实例. 作为经验, prototype scope 的bean适用于有状态的beans, 而 singleton scope适用于无状态的beans.

args:生成对象构造函数参数

props:注入内容,注入的内容可以在对象内部调用



lib2.js:

/**
 * Created by Administrator on 2016/5/3.
 */
var Bearcat = require('bearcat');
var EventEmitter = require('events').EventEmitter;
var Util = require('util');


var human = function () {
    this.name = "human1111";
    this.index = 0;
};
Util.inherits(human, EventEmitter);

human.prototype.start = function () {
    this.emit("addIndex", this.index);
    this.index++;
    console.log("emit index start");
};

human.prototype.getName = function () {

    this.on("addIndex", function (index) {
        console.log("index ", index);
    });
    return this.name;
};

module.exports = {
    id: "human",
    func: human
};

app.js:

/**
 * Created by Administrator on 2016/5/3.
 */

var BearCat = require("bearcat");
var Path = require("path");
var contextArray = [];

var context1 = require.resolve(Path.join(__dirname, "./context.json"));

contextArray.push(context1);


BearCat.createApp(contextArray);
BearCat.start(function () {
    var p= BearCat.getBean("person","zjw",25);
    console.log(p.toString());
    var h = BearCat.getBean("human");
    h.start();
    console.log(h.getName());
});


参考资料:https://github.com/bearcatjs/bearcat

https://github.com/bearcatjs/bearcat/wiki


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值