前端 MVC

Tags: js

文章内容大多来自学习摘记、实践思考。

MVC 是一个流行的软件架构。可以从 Ruby on Rails 获得许多有关 MVC 的基本设计原则,将其引入并支持 node 的 MVC 设计。Express 已经采用了路由的概念(Rails 的基本原则),还需要分离的模型:视图和控制器。接下来,创建 controllers、model、views 目录等,将现有的每个路由的方法调用转换为单独的函数然后导出,等操作。MVC 架构使得代码看起来干净又简单,并且扩展性更好。

  • Model
    • model 里存放的是「需要持久化的数据」(DO, domain object),而不是页面显示用的临时数据(VO, view object / ui state)。
    • model 里可以包含对 Ajax 请求参数的组装、处理。
    • 公共 model 抽取出来放一个地方;不同页面特有的 model 邻近相应 view 放置。
    • model 是否是 singleton 的?使用时需不需要 new ?
  • View
    • 页面全部组件化(参考react组件化思路)
    • 抽象出组件的方式尽量简单(react比angular组件简单)
    • 需要复用的代码片段、抽象成组件
  • controller
    • 内容应尽量少,在 controller 里设置页面显示用的运行时数据(VO, view object / ui state),持久化的数据从 model 里获取。
    • Any time you need to store information only for the lifetime of this application run, you should store it on a controller.

model 不同的设计思路

ember-data 处理方式:

  • DS.Model 用来创建数据模型。定义了需要呈现给用户的数据的属性和行为。
    • 不同模型之间会有关联关系:一对一,一对多,多对多。与后台数据库模型类似。原文翻译
    • 模型本身没有任何数据;模型只定义了其实例所具有的属性和行为,而这些实例被称为记录。
    • 记录是模型的实例,包含了从服务器端加载而来的数据。应用本身也可以创建新的记录,以及将新记录保存到服务器端。
  • DS.Store 中心数据仓库,是应用的所有数据的缓存。一般整个应用只有一个 store 生成,负责创建/删除/查找/过滤/定位 DS.Model 的实例。
    • 注意,重申下 Model 只是数据的属性和行为,Model 的实例 record 包含具体的数据,由 store 创建存储管理。
  • 利用不同的 Adapter 和不同服务端通信,如:HTTP、Websocket 等。

在 react.js 的 flux 等架构中,是不建议使用「fat model」的。model使用

fat model, skinny controller. the model should do the heavy lifting are:

  • Validation in the case of CRUD functionality and post methods.
  • Type-conversions and data manipulation.
  • Storing data in memory or in HTML5 databases to minimize server hits.

The server-side code mainly does model manipulation and notifications, and so having a fat model/thin controllers makes sense. The controller is essentially the router to the model.

业务场景

博客文章下边有一个 “like” 按钮。

  • 显示前十个喜欢此文章的用户。(对应一个 API)
  • 单独一个模块显示喜欢此文章的全部用户,带有分页。(对应另一个 API)
  • 点击 “like” 按钮,以上两个区域的数据改变。

这里对于点击了喜欢的用户,需要有个「model collection」,但是需要一个 model 或者是 两个 ?

It would be nice if those two lists corresponded to the same model collection, but this means the same model collection needs to be fed from two different API responses. Turns out, 1:1 correspondence between API responses and model objects doesn’t scale!

最近文章

2024-02-15 » 字节监控之旅
2024-01-06 » 如何做一个好的管理者
2023-12-23 » E2E测试实践