Skip to content

Commit 6665801

Browse files
committed
为 Model 基类定义一个静态块 defineAttributes
1 parent 7a9a283 commit 6665801

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

lib/defines/buildModelBase.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ function buildModelBase ({
2121
value: Model
2222
})
2323

24+
if (!this.constructor.definedAttributes) {
25+
// 如果尚未定义 definedAttributes,调用模型类的静态方法调用
26+
this.constructor.defineAttributes && this.constructor.defineAttributes()
27+
}
28+
2429
if (defineAttributesIn === 'object') {
2530
defineAttributes(this, attributesDefinition || this.constructor.definedAttributes)
2631
// 计算属性还是考虑定义在原型
@@ -94,6 +99,13 @@ function buildModelBase ({
9499
deleter.call(this, key)
95100
}
96101
}
102+
103+
static defineAttribute (name, options) {
104+
defineAttributes(this, { [name]: options })
105+
106+
this.definedAttributes = this.definedAttributes || {}
107+
Object.assign(this.definedAttributes, { [name]: options })
108+
}
97109
}
98110

99111
Model.defaultConfig = {
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const test = require('ava')
2+
const Model = require('../../lib/model')
3+
4+
class User extends Model {
5+
static defineAttributes () {
6+
this.defineAttribute('name', {})
7+
this.defineAttribute('age', {})
8+
}
9+
}
10+
11+
test('测试 defineAttributes 成功设置了属性定义', t => {
12+
const user = new User()
13+
user.attributes = {
14+
name: 'Jim',
15+
age: 18,
16+
foo: 'foo'
17+
}
18+
19+
t.is(user.name, 'Jim')
20+
t.is(user.age, 18)
21+
t.is(user.foo, undefined)
22+
})

0 commit comments

Comments
 (0)