Typography

活版印字


  • Home
  • Archive
  • Categories
  • Tags
  •  

© 2020 alincode

Theme Typography by Makito

Proudly published with Hexo

view model vs model

Posted at 2016-04-04 view model 

View Model

除了 MVC 之外,後來 Microsoft 又提出一個 model-view-view model (MVVM),view model 是一種 model 的變形,有時候你 view 需要的資料,不只會包含一個 model,又或者它僅需要部分的資料,因為有部分不能傳給使用者,例如資料庫中記錄的密碼或一些對使用者無意義的資料,但對系統有意義的資料。

Model

不太嚴謹的說法,可以直接對照到資料庫的 table

範例

改變前

User.js

1
2
3
4
5
6
7
8
9
10
11
module.exports = {
attributes: {
firstName: String,
lastName: String,
nickname: String,
email: String,
password: String,
address: String,
phone: String,
}
}

Profile.js

1
2
3
4
5
6
module.exports = {
attributes: {
image: String,
// ...略...
}
}

UserController.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
apiMe: async(req, res) => {
try {
if(!req.userId){
throw new Error('userId is null');
}

let user = await UserService.findById(req.userId);
let profile = await ProfileService.findByUesrId(req.userId);

user.toJSON();
profile.toJSON();

res.view('profile', {
email: user.email,
nickname: user.nickname,
image: profile.image,
//...略...
});
} catch (e) {
return res.serverError(e);
}
},

改變後

UserController.js

1
2
3
4
5
6
7
8
9
10
11
var userViewModel = require('../viewModels/UserViewModel.js')
apiMe: async(req, res) => {
try {
if(!req.userId){
throw new Error('userId is null');
}
res.view('profile', await userViewModel(req.userId));
} catch (e) {
return res.serverError(e);
}
},

UserViewModel.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
module.exports = async (userId) => {
let user = await UserService.findById(userId);
let profile = await ProfileService.findByUesrId(userId);

user.toJSON();
profile.toJSON();

return {
email: user.email,
nickname: user.nickname,
image: profile.image,
//...略...
}
}

結論

主要是好處是把 ViewModel 封裝起來,在其他地方也可以被重複使用。

補充

View:主要是將 model 呈現給使用者
Controller:會接收使用者輸入的資料,並決定要顯示哪個 view。

Share 

 Previous post: github 快速鍵 Next post: PM2 管理工具 

© 2020 alincode

Theme Typography by Makito

Proudly published with Hexo