我应该在Model还是ViewModel上实现业务逻辑 [英] Should I implement business logic on a Model or a ViewModel

查看:69
本文介绍了我应该在Model还是ViewModel上实现业务逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在MVVM应用程序中处理业务逻辑时.我应该在Model还是ViewModel上执行此操作?

When I'm processing business logic in an MVVM app. Should I do this on the Model or the ViewModel?

例如,如果我想在资产重估后重新计算成本,我是否应该对模型进行操作?

For example, if I want to re-calculate costs after an Asset has been re-valued, should I operate on the Model?

在ViewModel上执行此操作是否有优势?

Is there an advantage in doing this on the ViewModel instead?

如果我有ViewModels列表,但是我想将其转换为Models列表,以便可以进行一些处理,会发生什么情况?我可以将Model公开为ViewModel的属性(并使用该属性来构建Models列表).但这意味着View将能够访问原始Model的属性

What happens if I have a list of ViewModels, but I want to translate that into a list of Models so I can do some processing? I could expose the Model as a property of the ViewModel (and use that to build the list of Models). But that means that the View will be able to access properties of the original Model

推荐答案

模型的目的是代表(或建模)您的业务领域.因此,根据定义,业务逻辑将包含在模型中,而不是在ViewModel中.

The Model's purpose is to represent (or model) your business domain. Therefore, business logic by definition goes in the Model, not the ViewModel.

ViewModel的工作是公开Model的属性和字段,并准备它们供View使用.

The job of the ViewModel is to expose properties and fields of the Model, and prepare them for consumption by the View.

例如,想象一个银行应用程序.该模型可以代表一个帐户.该模型可能具有帐户余额.该模型的工作可能是跟踪余额并确保维持某些不变性(例如不允许提取大于余额的提款).ViewModel的工作可能是将天平变成一个字符串,用作View中的绑定.

For instance, picture a banking application. The Model may represent an account. Perhaps the Model has an account balance. The job of the Model may be to track the balance and make sure certain invariants are maintained (such as not allowing a withdrawal that is larger than the balance). The job of the ViewModel may be to turn the balance into a string that is used as a binding in the View.

您希望在ViewModel中保留尽可能多的逻辑,以使您的代码可重用和松耦合.

You want to keep as much logic out of the ViewModel as possible to keep your code reusable and loosely coupled.

这篇关于我应该在Model还是ViewModel上实现业务逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆