javacript中的mvc设计模式
以下内容为原创翻译,翻译不对的地方还请原谅,凑合着看吧。
原文网址是:
来源: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的设计很简单-数据存储在一个数组属性和一个已经选择的属性当中。代码如下:
/** * The Model. Model stores items and notifies
* observers about changes.
*/
function ListModel(items) {
this._items = items;
this._selectedIndex = -1; this.itemAdded = new Event(this);
this.itemRemoved = new Event(this);
this.selectedIndexChanged = new Event(this);
} ListModel.prototype = {
getItems : function () {
return [].concat(this._items);
}, addItem : function (item) {
this._items.push(item);
this.itemAdded.notify({ item : item });
}, removeItemAt : function (index) {
var item; item = this._items[index];
this._items.splice(index, 1);
this.itemRemoved.notify({ item : item });
if (index === this._selectedIndex) {
this.setSelectedIndex(-1);
}
}, getSelectedIndex : function () {
return this._selectedIndex;
}, setSelectedIndex : function (index) {
var previousIndex; previousIndex = this._selectedIndex;
this._selectedIndex = index;
this.selectedIndexChanged.notify({ previous : previousIndex });
}
};
事件是一个简单的类,主要用来实现观察者模式:
function Event(sender) {
this._sender = sender;
this._listeners = [];
}
Event.prototype = {
attach : function (listener) {
this._listeners.push(listener);
},
notify : function (args) {
var index;
for (index = 0; index < this._listeners.length; index += 1) {
this._listeners[index](this._sender, args);
}
}
};
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类:
/**
* The View. View presents the model and provides
* the UI events. The controller is attached to these
* events to handle the user interraction.
*/
function ListView(model, elements) {
this._model = model;
this._elements = elements; this.listModified = new Event(this);
this.addButtonClicked = new Event(this);
this.delButtonClicked = new Event(this); var _this = this; // attach model listeners
this._model.itemAdded.attach(function () {
_this.rebuildList();
});
this._model.itemRemoved.attach(function () {
_this.rebuildList();
}); // attach listeners to HTML controls
this._elements.list.change(function (e) {
_this.listModified.notify({ index : e.target.selectedIndex });
});
this._elements.addButton.click(function () {
_this.addButtonClicked.notify();
});
this._elements.delButton.click(function () {
_this.delButtonClicked.notify();
});
} ListView.prototype = {
show : function () {
this.rebuildList();
}, rebuildList : function () {
var list, items, key; list = this._elements.list;
list.html(''); items = this._model.getItems();
for (key in items) {
if (items.hasOwnProperty(key)) {
list.append($('<option>' + items[key] + '</option>'));
}
}
this._model.setSelectedIndex(-1);
}
}; /**
* The Controller. Controller responds to user actions and
* invokes changes on the model.
*/
function ListController(model, view) {
this._model = model;
this._view = view; var _this = this; this._view.listModified.attach(function (sender, args) {
_this.updateSelected(args.index);
}); this._view.addButtonClicked.attach(function () {
_this.addItem();
}); this._view.delButtonClicked.attach(function () {
_this.delItem();
});
} ListController.prototype = {
addItem : function () {
var item = window.prompt('Add item:', '');
if (item) {
this._model.addItem(item);
}
}, delItem : function () {
var index; index = this._model.getSelectedIndex();
if (index !== -1) {
this._model.removeItemAt(this._model.getSelectedIndex());
}
}, updateSelected : function (index) {
this._model.setSelectedIndex(index);
}
};
当然,mvc类都需要实例化。你可以通过以下代码实例化:
$(function () {
var model = new ListModel(['PHP', 'JavaScript']),
view = new ListView(model, {
'list' : $('#list'),
'addButton' : $('#plusBtn'),
'delButton' : $('#minusBtn')
}),
controller = new ListController(model, view);
view.show();
});
html部分:(引入jquery就能运行了)
<select id="list" size="10" style="width: 15em"></select><br/>
<button id="plusBtn"> + </button>
<button id="minusBtn"> - </button>
javacript中的mvc设计模式的更多相关文章
- 第80节:Java中的MVC设计模式
第80节:Java中的MVC设计模式 前言 了解java中的mvc模式.复习以及回顾! 事务,设置自动连接提交关闭. setAutoCommit(false); conn.commit(); conn ...
- 0112.1——iOS开发之理解iOS中的MVC设计模式
模型-视图-控制器(Model-View-Controller,MVC)是Xerox PARC在20世纪80年代为编程语言Smalltalk-80发明的一种软件设计模式,至今已广泛应用于用户交互应用程 ...
- iOS开发之理解iOS中的MVC设计模式
模型-视图-控制器(Model-View-Controller,MVC)是Xerox PARC在20世纪80年代为编程语言Smalltalk-80发明的一种软件设计模式,至今已广泛应用于用户交互应用程 ...
- [原创]java WEB学习笔记18:java EE 中的MVC 设计模式(理论)
本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...
- iOS开发中的MVC设计模式
我们今天谈谈cocoa程序设计中的 模型-视图-控制器(MVC)范型.我们将从两大方面来讨论MVC: 什么是MVC? M.V.C之间的交流方式是什么样子的? 理解了MVC的概念,对cocoa程序开发是 ...
- IOS 中的MVC设计模式
- 谈谈JAVA工程狮面试中经常遇到的面试题目------什么是MVC设计模式
作为一名java工程狮,大家肯定经历过很多面试,但每次几乎都会被问到什么是MVC设计模式,你是怎么理解MVC的类似这样的一系列关于MVC的问题. [出现频率] [关键考点] MVC的含义 MVC的结构 ...
- iOS开发——高级篇——iOS中常见的设计模式(MVC/单例/委托/观察者)
关于设计模式这个问题,在网上也找过一些资料,下面是我自己总结的,分享给大家 如果你刚接触设计模式,我们有好消息告诉你!首先,多亏了Cocoa的构建方式,你已经使用了许多的设计模式以及被鼓励的最佳实践. ...
- Java Web开发中MVC设计模式简介
一.有关Java Web与MVC设计模式 学习过基本Java Web开发的人都已经了解了如何编写基本的Servlet,如何编写jsp及如何更新浏览器中显示的内容.但是我们之前自己编写的应用一般存在无条 ...
随机推荐
- c# 语法5.0 新特性 转自网络
本专题概要: 引言 同步代码存在的问题 传统的异步编程改善程序的响应 C# 5.0 提供的async和await使异步编程更简单 async和await关键字剖析 小结 一.引言 在之前的C#基础知 ...
- NSString和NSArray平时练习总结
/*************************字符串练习****************************/ //创建字符串 //1.快速创建 NSString *str1 = @&quo ...
- struts2的包和命名空间
struts2提供了命名空间的功能,主要是为了处理同一个WEB应用中包含同名Action的情形.struts2以命名空间的方式来管理Action,同一个命名空间里不能有同名的Action,不同的命名空 ...
- xmlspy注册后打开报错的解决办法
XMLSpy 2011中文版破解补丁使用方法 1.如果你下载的版本是r2sp1的话(r2不用此步骤),先用补丁主程序(altova.xmlspy.v2011r2sp1b-patch.exe).2.XM ...
- Windows Phone 中查找可视化树中的某个类型的元素
private void StackPanel_Tap(object sender, TappedRoutedEventArgs e) { //获取到的对象是ListBoxItem ListBoxIt ...
- Linux下解决apache 报 403 forbidden 错
三步搞定: 1. 打开终端 2. 输入 chcon -R -t httpd_sys_content_t /var/www/html # 后面的/var/www/html是网站的默认目录,可以根据自己的 ...
- tp中让头疼似懂非懂的create
项目中多次用到create() 只能它是表单验证,不过好出错,痛下心扉好好了解理解它的来龙去脉和所用的用法 一:通过create() 方法或者 赋值的方法生成数据对象,然后写入数据库 $model = ...
- WinForm TreeView节点重绘,失去焦点的高亮显示
当用户焦点离开TreeView时,TreeView选中节点仍然高亮,但是颜色符合主题. 设置TreeView.HideSelection = False;可让选中节点保持高亮. 添加重绘事件 Tree ...
- .Net 将一个DataTable分解成多个DataTable
这两天遇到一个问题,我们所接触 的一个系统在导出数据到Excel的时候,产生了内存溢出的错误.原因在于数据过大,它导出是将所有数据存放在一个DataSet的一个表中,再将这个数 据集放入session ...
- ajax对一些没有接口的数据进行分析和添加方法
对于一些没有接口的数据进行分析和添加方法: <script src="ajax.js"><script>//插入ajax文件 <script> ...