AS3 一个基本 MVC 例子

原文:Basic Model View Controller (MVC) Example AS3 作者:Florian Spier 翻译

Hello folks,

I was searching the web for an example you could call MVC for dummies… What I found were mostly complex examples decorating the basic MVC  relevant code with a lot of other stuff, which makes it difficult to focus on and understand the pure MVC thing.

大家好,我本来想在网上搜些类似叫做 MVC 傻瓜教程的例子 … 可是结果我找到的大部分复杂的例子,在基本 MVC 上装饰了很多很多其他东西,使得很难着重理解最纯粹的 MVC。

Therefore i decided to code a very basic and minimalistic MVC example to share it with you. The result is a tiny slideshow application that allows you to navigate through a group of pictures. Very easy thing nobody would ever use a MVC pattern for…, but i hope this simple MVC will be a good starting point for someone trying to understand the Model View Controller Design Pattern.

因此,我决定编写一个非常基本和 最小化的 MVC 例子 给大家分享。这是一个微型的 slideshow 应用,可以用来导览一组图片。虽然这种非常简单的东西可能没有人用 MVC 模式去实现过……但是我希望这个简单的 MVC 能给某些人提供一个好的入门方式,去理解 Model View Controller 设计模式。

Here you can watch a online demo (you can switch to View Source Mode via right-click). View Source Mode gives you the possibility to download the source files.

你可以查看这个 在线 demo (点右键可以选择切换到 View Source 模式). 可以在 View Source 模式里下载 源代码

By exploring the Actionscript Classes of the slideshow application you can easily understand the distribution of tasks within the the MVC pattern:

查看 slideshow 应用程序的 AS 代码你可以很容易理解 MVC 模式的任务分布:

Model: holds the data of the slideshow (e.g.  the array of image filepaths or the current Image Url). The Model contains functions to manipulate models Data and dispatches update-events as soon as its data changes.

模型 l(Model):保持 slideshow 的数据(如:图片文件路径的数组或者当前图片的 URL)。模型包含维护模型数据 (Data) 的函数,以及当数据改变时分派“更新事件 (update-events)”。

View: holds references of both Model and Contoller. The View connects to the data of the Model as soon as it receives notification by the Model (in this case by listening for the Model´s update-events). The View accepts user interactions (here of the back and next buttons) and can call the corresponding functions of the Controller.

视图(View):保持模型和控制器的引用。一旦接收到模型的通知,视图就去访问模型的数据(通过监听模型的“更新事件”)。视图接受用户的交互(如:例子里的前进后退按钮),并且调用控制器的“通信函数 (corresponding functions)”。

Controller: Controller contains functions which are called directly by the View or are triggered by Model´s update-events. The controller contains the main logic of the application.

控制器(Controller):控制器含有提供给 View 直接调用的函数,被模型的“更新事件”触发的函数。控制器含有应用程序的主逻辑。

Sounds not too difficult… and with this easy MVC example you get the quintessence of MVC on a plate.

听起来不难……而且这个简单的 MVC 例子会让你很容易理解 MVC 的精华。