-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
120 lines (98 loc) · 3.14 KB
/
index.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
108
109
110
111
112
113
114
115
116
117
118
119
120
var Emitter = require("emitter-component"),
is = require("istype"),
statics = require("./static"),
Result = require("result-brighthas"),
default_validator = require("./validators/default"),
convert_validator = require("./validators/convert"),
readonly_validator = require("./validators/readonly"),
type_validator = require("./validators/type"),
required_validator = require("./validators/required"),
length_validator = require("./validators/length"),
validator_validator = require("./validators/validator"),
bindSubEvent = require("./bindSubEvent"),
proto = require("./proto"),
ModelClasses = {}, types = require("./types");
function createModel(name) {
function generateAttr(args) {
var attrs = [];
var currentAttr = null;
args.forEach(function(arg) {
if (is.type(arg) === "string") {
currentAttr = {
name: arg
};
attrs.push(currentAttr);
} else {
currentAttr.option = arg;
}
});
attrs.forEach(function(attr) {
Model.attr(attr.name, attr.option);
});
}
function Model(attrs) {
if (!(this instanceof Model)) {
return new Model(attrs);
} else {
Emitter(this);
var self = this;
this._instant = true;
this.attrs = attrs || {};
this.oattrs = {};
this.result = new Result();
var errorFun = this.result.error.bind(this.result);
this.error = this.result.error = function(attr, message) {
if(arguments.length === 0){
return errorFun();
}else if(arguments.length === 1){
return errorFun(attr);
}else{
var option = self.model.attrs[attr];
var err = errorFun(attr);
if (option && option.message) {
if (!err || err.length === 0) {
errorFun(attr, option.message);
}
} else {
errorFun(attr, message);
}
}
};
var keys = Object.keys(this.model.attrs);
this.model.emit("creating", this);
this.validate();
if (!this.hasError()) {
this.oattrs = attrs || {};
var names = this.model.getComplexAttrNames();
bindSubEvent(this, names);
this.model.emit("created", this);
}
this.attrs = {};
}
}
Emitter(Model);
Model.modelName = name;
Model.attrs = {};
Model.validators = [];
Model.prototype.model = Model;
ModelClasses[name] = Model;
for (var key in statics) {
Model[key] = statics[key];
}
for (var key in proto) {
Model.prototype[key] = proto[key];
}
generateAttr([].slice.call(arguments, 1));
Model.use(convert_validator);
Model.use(type_validator);
Model.use(readonly_validator);
Model.use(default_validator);
Model.use(required_validator);
Model.use(length_validator);
Model.use(validator_validator);
return Model;
}
createModel.get = function(name) {
return ModelClasses[name]
}
module.exports = createModel;