javascript - Knockout.js 中的“模型”和 'ViewModel'

标签 javascript model-view-controller mvvm knockout.js architectural-patterns

在 MVC 中,“Model”只是数据的代码表示(例如,在 ASP.NET MVC 中,它是一个具有相应字段的类)。

但是在 Knockout 中(使用 MVVM),我看到带有字段的对象称为“ViewModel”。来自官方 KO 文档:

A model: your application’s stored data. This data represents objects and operations in your business domain (e.g., bank accounts that can perform money transfers) and is independent of any UI. When using KO, you will usually make Ajax calls to some server-side code to read and write this stored model data.

A view model: a pure-code representation of the data and operations on a UI. For example, if you’re implementing a list editor, your view model would be an object holding a list of items, and exposing methods to add and remove items.

从示例中可以看出,ViewModel 是具有字段的对象,保存数据,通常由 MVC 中的模型完成:

var myViewModel = {
    personName: ko.observable('Bob'),
    personAge: ko.observable(123)
};

所以我有点迷路了。 “模型”和“ View 模型”在 Knockout.js 域中到底是什么意思?

最佳答案

在 JavaScript 实现的 MVVM 模式中,“模型”部分通常由 Web API 提供。提供给页面的数据是模型。现在,一旦数据在 JavaScript 中,它是否包含在单独的模型对象中 - 那是另一回事了。

通常, View 模型只是一个添加了属性和函数的模型,以支持应用它的特定 View 。客户端计算、下拉查找值、客户端验证例程等。在这种情况下, View 模型可能如下所示:

var vm = {
    save: function(){ save logic... },
    cancel: function(){ cancel logic... },
    states: ko.observable(), //list of states for state dropdown
    customerId: ko.observable(),
    customerFirstName: ko.observable(),
    customerLastName: ko.observable()
};

其他时候,模型将在单独的对象中维护。在这种情况下, View 模型可能如下所示:

var customerModel = getCustomerFromDataSource();
var vm = {
    save: function(){ save logic... },
    cancel: function(){ cancel logic... },
    states: ko.observable(), //list of states for state dropdown
    customer: customerModel
};

要记住的主要事情是模型是数据, View 模型是使您的模型可用于 View 的层(通常通过数据绑定(bind))。有时模型可能是一个单独的类;其他时候,模型只是 View 模型中的一组已知属性。

关于javascript - Knockout.js 中的“模型”和 'ViewModel',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20608266/

相关文章:

spring - DispatcherServlet 如何准确地确定要调用哪个 Controller ?

java - 在这种情况下我需要制作自定义事件吗?

android - 未知属性 onItemSelected/onCheckedChanged

c# - WPF DataGrid - 数据绑定(bind)到 CellTemplates DataTemplate 中的 DataTable 单元格

javascript - 页面加载时执行 jQuery Popup?

javascript - 多行字符串的无效或意外标记

ruby-on-rails - 从 Rails 中不同命名空间中的另一个 Controller 重定向/调用方法

wpf - MVVM 和 UniformGrid 的数据绑定(bind)

javascript - BxSlider—单击“幻灯片”查看下一个

javascript - 制作一个创建按钮 HTML/JS 的函数