以下内容为原创翻译,翻译不对的地方还请原谅,凑合着看吧。

原文网址是:

来源:http://www.alexatnet.com/articles/model-view-controller-mvc-javascript

这篇文章主要讲述了 js中的 mvc 设计模式。

实现目标截图:

我之所以喜欢javascript是因为它可以称之为世界上最灵活的语言。通过javascript,开发者可以通过面向对象或者面向过程的方式创建应用程序。它可以支持任何我所知道的程序设计风格以及程序技术。我曾经见识过面向过程,面向对象以及面向方面的程序片段。开发者甚至可以使用函数式编程技术来创建应用程序

我写这篇文章的目的是通过一个简单的javascript组件让你知道mvc有多么强大。这个组件式一个可编辑条目的listBox:使用者可以选择一条数据,也可以移除数据抑或是增加新数据到列表中。组件将包含三个类,遵循mvc规则

我希望这篇文章对你来说有用。如果你能按照我的例子动手做一遍并将它转化成你需要的那是最好不过了。你可以通过:动手,动脑,编辑器以及网络浏览器(如谷歌浏览器)来创建以及跑通你的javascript程序。

下面,我将在代码中使用MVC设计模式,但是需要先描述下。正如你所知道的,模式的名字是基于它主要的内容划分的:Model层将存放应用数据;View层主要将Model层数据以合适的形式展现出来;Controller主要用来更新Model。维基百科中定义了传统的MVC结构如下:

  • Model - The domain-specific representation of the information on which the application operates. The model is another name for the domain layer. Domain logic adds meaning to raw data (e.g., calculating if today is the user's birthday, or the totals, taxes and shipping charges for shopping cart items).
  • View - Renders the model into a form suitable for interaction, typically a user interface element. MVC is often seen in web applications, where the view is the HTML page and the code which gathers dynamic data for the page.
  • Controller - Processes and responds to events, typically user actions, and invokes changes on the model and perhaps the view.

组件的数据是一个list列表,条目可以被选中以及删除。因此Model的设计很简单-数据存储在一个数组属性和一个已经选择的属性当中。代码如下:

  1. /**
  2.  
  3. * The Model. Model stores items and notifies
  4. * observers about changes.
  5. */
  6. function ListModel(items) {
  7. this._items = items;
  8. this._selectedIndex = -1;
  9.  
  10. this.itemAdded = new Event(this);
  11. this.itemRemoved = new Event(this);
  12. this.selectedIndexChanged = new Event(this);
  13. }
  14.  
  15. ListModel.prototype = {
  16. getItems : function () {
  17. return [].concat(this._items);
  18. },
  19.  
  20. addItem : function (item) {
  21. this._items.push(item);
  22. this.itemAdded.notify({ item : item });
  23. },
  24.  
  25. removeItemAt : function (index) {
  26. var item;
  27.  
  28. item = this._items[index];
  29. this._items.splice(index, 1);
  30. this.itemRemoved.notify({ item : item });
  31. if (index === this._selectedIndex) {
  32. this.setSelectedIndex(-1);
  33. }
  34. },
  35.  
  36. getSelectedIndex : function () {
  37. return this._selectedIndex;
  38. },
  39.  
  40. setSelectedIndex : function (index) {
  41. var previousIndex;
  42.  
  43. previousIndex = this._selectedIndex;
  44. this._selectedIndex = index;
  45. this.selectedIndexChanged.notify({ previous : previousIndex });
  46. }
  47. };

事件是一个简单的类,主要用来实现观察者模式:

  1. function Event(sender) {
  2. this._sender = sender;
  3. this._listeners = [];
  4. }
  5.  
  6. Event.prototype = {
  7. attach : function (listener) {
  8. this._listeners.push(listener);
  9. },
  10. notify : function (args) {
  11. var index;
  12.  
  13. for (index = 0; index < this._listeners.length; index += 1) {
  14. this._listeners[index](this._sender, args);
  15. }
  16. }
  17. };

View类需要定义可交互的控件。有很多界面都可以完成这个任务,但是我更喜欢简单一点的。我想把items放入一个listbox控件中,底下有两个按钮,分别是:+ 用来增加 -用来删除,另外listbox控件本身支持选中item。

A View class is tightly bound with a Controller class, which "... handles the input event from the user interface, often via a registered handler or callback" (from wikipedia.org).

下面是View类和Controller类:

  1. /**
  2. * The View. View presents the model and provides
  3. * the UI events. The controller is attached to these
  4. * events to handle the user interraction.
  5. */
  6. function ListView(model, elements) {
  7. this._model = model;
  8. this._elements = elements;
  9.  
  10. this.listModified = new Event(this);
  11. this.addButtonClicked = new Event(this);
  12. this.delButtonClicked = new Event(this);
  13.  
  14. var _this = this;
  15.  
  16. // attach model listeners
  17. this._model.itemAdded.attach(function () {
  18. _this.rebuildList();
  19. });
  20. this._model.itemRemoved.attach(function () {
  21. _this.rebuildList();
  22. });
  23.  
  24. // attach listeners to HTML controls
  25. this._elements.list.change(function (e) {
  26. _this.listModified.notify({ index : e.target.selectedIndex });
  27. });
  28. this._elements.addButton.click(function () {
  29. _this.addButtonClicked.notify();
  30. });
  31. this._elements.delButton.click(function () {
  32. _this.delButtonClicked.notify();
  33. });
  34. }
  35.  
  36. ListView.prototype = {
  37. show : function () {
  38. this.rebuildList();
  39. },
  40.  
  41. rebuildList : function () {
  42. var list, items, key;
  43.  
  44. list = this._elements.list;
  45. list.html('');
  46.  
  47. items = this._model.getItems();
  48. for (key in items) {
  49. if (items.hasOwnProperty(key)) {
  50. list.append($('<option>' + items[key] + '</option>'));
  51. }
  52. }
  53. this._model.setSelectedIndex(-1);
  54. }
  55. };
  56.  
  57. /**
  58. * The Controller. Controller responds to user actions and
  59. * invokes changes on the model.
  60. */
  61. function ListController(model, view) {
  62. this._model = model;
  63. this._view = view;
  64.  
  65. var _this = this;
  66.  
  67. this._view.listModified.attach(function (sender, args) {
  68. _this.updateSelected(args.index);
  69. });
  70.  
  71. this._view.addButtonClicked.attach(function () {
  72. _this.addItem();
  73. });
  74.  
  75. this._view.delButtonClicked.attach(function () {
  76. _this.delItem();
  77. });
  78. }
  79.  
  80. ListController.prototype = {
  81. addItem : function () {
  82. var item = window.prompt('Add item:', '');
  83. if (item) {
  84. this._model.addItem(item);
  85. }
  86. },
  87.  
  88. delItem : function () {
  89. var index;
  90.  
  91. index = this._model.getSelectedIndex();
  92. if (index !== -1) {
  93. this._model.removeItemAt(this._model.getSelectedIndex());
  94. }
  95. },
  96.  
  97. updateSelected : function (index) {
  98. this._model.setSelectedIndex(index);
  99. }
  100. };

当然,mvc类都需要实例化。你可以通过以下代码实例化:

  1. $(function () {
  2. var model = new ListModel(['PHP', 'JavaScript']),
  3. view = new ListView(model, {
  4. 'list' : $('#list'),
  5. 'addButton' : $('#plusBtn'),
  6. 'delButton' : $('#minusBtn')
  7. }),
  8. controller = new ListController(model, view);
  9.  
  10. view.show();
  11. });
  1. html部分:(引入jquery就能运行了)​
  1. <select id="list" size="10" style="width: 15em"></select><br/>
  2. <button id="plusBtn"> + </button>
  3. <button id="minusBtn"> - </button>

javacript中的mvc设计模式的更多相关文章

  1. 第80节:Java中的MVC设计模式

    第80节:Java中的MVC设计模式 前言 了解java中的mvc模式.复习以及回顾! 事务,设置自动连接提交关闭. setAutoCommit(false); conn.commit(); conn ...

  2. 0112.1——iOS开发之理解iOS中的MVC设计模式

    模型-视图-控制器(Model-View-Controller,MVC)是Xerox PARC在20世纪80年代为编程语言Smalltalk-80发明的一种软件设计模式,至今已广泛应用于用户交互应用程 ...

  3. iOS开发之理解iOS中的MVC设计模式

    模型-视图-控制器(Model-View-Controller,MVC)是Xerox PARC在20世纪80年代为编程语言Smalltalk-80发明的一种软件设计模式,至今已广泛应用于用户交互应用程 ...

  4. [原创]java WEB学习笔记18:java EE 中的MVC 设计模式(理论)

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

  5. iOS开发中的MVC设计模式

    我们今天谈谈cocoa程序设计中的 模型-视图-控制器(MVC)范型.我们将从两大方面来讨论MVC: 什么是MVC? M.V.C之间的交流方式是什么样子的? 理解了MVC的概念,对cocoa程序开发是 ...

  6. IOS 中的MVC设计模式

  7. 谈谈JAVA工程狮面试中经常遇到的面试题目------什么是MVC设计模式

    作为一名java工程狮,大家肯定经历过很多面试,但每次几乎都会被问到什么是MVC设计模式,你是怎么理解MVC的类似这样的一系列关于MVC的问题. [出现频率] [关键考点] MVC的含义 MVC的结构 ...

  8. iOS开发——高级篇——iOS中常见的设计模式(MVC/单例/委托/观察者)

    关于设计模式这个问题,在网上也找过一些资料,下面是我自己总结的,分享给大家 如果你刚接触设计模式,我们有好消息告诉你!首先,多亏了Cocoa的构建方式,你已经使用了许多的设计模式以及被鼓励的最佳实践. ...

  9. Java Web开发中MVC设计模式简介

    一.有关Java Web与MVC设计模式 学习过基本Java Web开发的人都已经了解了如何编写基本的Servlet,如何编写jsp及如何更新浏览器中显示的内容.但是我们之前自己编写的应用一般存在无条 ...

随机推荐

  1. 移动开发Html 5前端性能优化指南

    详细内容请点击 PC优化手段在Mobile侧同样适用在Mobile侧我们提出三秒种渲染完成首屏指标基于第二点,首屏加载3秒完成或使用Loading基于联通3G网络平均338KB/s(2.71Mb/s) ...

  2. “System.Exception: System.Data.OracleClient 需要 Oracle 客户端软件 8.1.7 或更高版本” 的解决方案

    在项目部署过程中ORACLE客户端多次会遇"System.Exception: System.Data.OracleClient 需要 Oracle 客户端软件 8.1.7 或更高版本&qu ...

  3. PHP和CS的引用传值

    PHP的引用传值 function change_value($num){ $num+=2; } $age = 3; change_value(&$age); echo $age; CS的引用 ...

  4. ORACLE 数据库概述以及Oracel数据库的安装、卸载、使用

    一:Orcale简介 1.发展史 1978年,Orcale诞生 1982年,Orcale3推出了,它是第一个能够运行在大型机和小型机上的关系型数据库 1997年,Orcale公司推出了基于java语言 ...

  5. php数组编码转换函数的示例

    场景说明/问题描述: Ajax提交页面编码为gb2312,数据库编码为utf8,在不更改页面及数据库编码的情况下插入数据. 自定义函数:  代码如下 复制代码 function array_iconv ...

  6. 6步图文教你优化myeclipse2014

    MyEclipse 2014优化速度方案仍然主要有这么几个方面:去除无需加载的模块.取消冗余的配置.去除不必要的检查.关闭更新. 第一步: 去除不需要加载的模块 一个系统20%的功能往往能够满足80% ...

  7. iOS-GCD多线程

    GCD GCD -- Grand Central Dispatch 是基于C语言的底层API 用Block定义任务,将任务添加到线程中使用.集中管理 1.GCD的执行函数 //同步 dispatch_ ...

  8. 【学习笔记】【C语言】变量

    1. 什么是变量 当一个数据的值需要经常改变或者不确定时,就应该用变量来表示.比如游戏积分. 2. 定义变量 1> 目的 任何变量在使用之前,必须先进行定义. 定义变量的目的是:在内存中分配一块 ...

  9. 位图文件格式及linux下C语言来操作位图文件

    说到图片,位图(Bitmap)当然是最简单的,它是Windows显示图片的基本格式,其文件扩展名为*.BMP.由于没有经过任何的压缩,故BMP图片往往很大.在Windows下,任何格式的图片文件都要转 ...

  10. EasyUI form ajax submit到MVC后,在IE下提示下载内容的解决办法

    问题描述: 项目环境为,.Net Mvc5+EF6……前端框架使用的是EasyUI v1.4.4. 在视图页面中,使用form的submit方法提交表单数据时,如果是使用IE的话,请求成功后IE会提示 ...