-
Notifications
You must be signed in to change notification settings - Fork 0
/
plane.js
107 lines (101 loc) · 2.33 KB
/
plane.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/**
* auto detect dir and parse every file to reg events
* rules:
* exports.evt_click stand for event "click" , casesensitive
* exports.evt_click_dot stand for event "click.dot" , casesensitive
**/
var fs = require('fs');
var xtower = require('./lib/xtower');
var gEvts = {
detectDir:'_detect_dir',
regEvt:'_reg_evt',
loadEvt:'_load_evt',
complete:'_complete_load',
detectDirCB:'_detect_dir_cb'
};
var assemleFile = function() {
var fullPath = '';
for(var i=0;i<arguments.length;i++) {
fullPath += arguments[i] + '/';
};
return fullPath.replace(/\/\/+/g,'/').replace(/\/$/g,'');
};
var isRegProp = function(prop){
if(!prop) {
return false;
}
return 0 == prop.indexOf('evt_');
};
var formatProp = function(prop) {
if(!prop) {
return '';
}
return prop.replace(/^evt_(.*)$/,'$1').replace(/_/g,'.');
};
var isFSNameCorrect = function(name) {
return null != /\.js$/g.exec(name)
};
/**
* input dirname,relative to this file
* output [files]
*/
var detectDir = function(tower,path) {
fs.readdir(path,function(error,files){
if(error) {
console.error('directory not exits %s',path);
return;
}
if(!files || 0 == files.length) {
console.error('no files found at %s',path);
return;
}
for(var i=0;i<files.length;i++) {
tower.fire(gEvts.detectDirCB,assemleFile(path,files[i]));
}
});
};
xtower.on(gEvts.detectDir,detectDir);
var regEvt = function(tower,name,cb){
console.info('reg event "%s"',name);
tower.on(name,cb);
};
xtower.on(gEvts.regEvt,regEvt);
/**
* parse every file and reg every method to tower
*/
var loadEvt = function(tower,file){
console.log('load file success[%s]',file);
var obj = require(file);
for(var i in obj) {
if(!isRegProp(i)) {
continue;
}
tower.fire(gEvts.regEvt,formatProp(i),obj[i]);
}
};
xtower.on(gEvts.loadEvt,loadEvt);
exports.fly = function(path,cb){
xtower.on(gEvts.complete,cb);
xtower.on(gEvts.detectDirCB,function(tower,file) {
if(!file) {
console.error("[%s] detect error",file);
return;
}
fs.stat(file,function(error,stats) {
if(error) {
return;
}
// if file fire loadEvt
if(stats.isFile()) {
if(!isFSNameCorrect(file)) {
return;
}
tower.fire(gEvts.loadEvt,file);
} else if(stats.isDirectory()) {
tower.fire(gEvts.detectDir,file);
}
});
});
xtower.fire(gEvts.detectDir,assemleFile(path));
xtower.fire(gEvts.complete);
};