`
lmh2072005
  • 浏览: 114049 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Model-View-Controller (MVC) with JavaScript

    博客分类:
  • js
阅读更多

转自:http://www.alexatnet.com/content/model-view-controller-mvc-javascript

 

The article describes an implementation of Model-View-Controller software design pattern in JavaScript.

 

I like JavaScript programming, because it is the most flexible language in the world. With the JavaScript language developers can create applications either in procedural or object-oriented style. It supports almost all programming styles and techniques that I know. I've seen procedural, object-oriented, aspect-oriented JavaScript code snippets. A determined developer can even use functional programming techniques in JavaScript applications.

My goal for this article is to write a simple JavaScript component that can show a power of the language. The component is a kind of the HTML ListBox ("select" HTML tag) control with an editable list of items: the user can select item and remove it or add new items into the list. Component will consist of three classes that implement the Model-View-Controller design pattern.

I hope, this article can be just a good reading for you, but it would be much better if you consider running the example and adapting it to you needs. I believe you have everything to create and run JavaScript programs: brains, hands, text editor (notepad), and Internet browser (IE or Firefox).

The Model-View-Controller pattern, which I'm about to use in the code, requires some description here. As you may know, the name of the pattern is based on the names of its main parts: Model, which stores an application data model; View, which renders Model for an appropriate representation; and Controller, which updates Model. Wikipedia defines typical components of the Model-View-Controller architecture as follows:

  • 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.

The data of the component is a list of items, in which one particular item can be selected and deleted. So, the model of the component is very simple - it is stored in an array property and selected item property; and here it is:

 

/**
 * The Model. Model stores items and notifies
 * observers about changes.
 */
var ListModel = function (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 = 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 = this._selectedIndex;
        this._selectedIndex = index;
        this.selectedIndexChanged.notify({previous: previousIndex});
    }
 
}; 

 

Event is a simple class for implementing the Observer pattern:

 

var Event = function (sender) {
    this._sender = sender;
    this._listeners = [];
};
 
Event.prototype = {
    attach : function (listener) {
        this._listeners.push(listener);
    },
    notify : function (args) {
        for (var i = 0; i < this._listeners.length; i++) {
            this._listeners[i](this._sender, args);
        }
    }
};

 

The View class requires defining controls for interacting with. There are numerous alternatives of interface for the task, but I prefer a most simple one. I want my items to be in a Listbox control and two buttons below it: "plus" button for adding items and "minus" for removing selected item. The support for selecting an item is provided by Listbox's native functionality. 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).

Here are the View and Controller classes:

 

var ListView = function (model, controller, elements) {
    this._model = model;
    this._controller = controller;
    this._elements = elements;
 
    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._controller.updateSelected(e);
    });
 
};
 
 
ListView.prototype = {
 
    show : function () {
        this.rebuildList();
        var e = this._elements;
        var _this = this;
        e.addButton.click(function () { _this._controller.addItem() });
        e.delButton.click(function () { _this._controller.delItem() });
    },
 
    rebuildList : function () {
        var list = this._elements.list;
        list.html('');
        var items = this._model.getItems();
        for (var key in items)
            list.append($('<option>' + items[key] + '</option>'))
        this._model.setSelectedIndex(-1);
    }
 
};
 
var ListController = function (model) {
    this._model = model;
};
 
ListController.prototype = {
 
    addItem : function () {
        var item = prompt('Add item:', '');
        if (item)
            this._model.addItem(item);
    },
 
    delItem : function () {
        var index = this._model.getSelectedIndex();
        if (index != -1)
            this._model.removeItemAt(this._model.getSelectedIndex());
    },
 
    updateSelected : function (e) {
        this._model.setSelectedIndex(e.target.selectedIndex);
    }
 
};

 

And of course, the Model, View, and Controller classes should be instantiated. The sample, which you can below, uses the following code to instantiate and configure the classes:

 

$(function () {
    var model = new ListModel(['PHP', 'JavaScript']);
    var view = new ListView(model, new ListController(model),
        {
            'list' : $('#list'),
            'addButton' : $('#plusBtn'),
            'delButton' : $('#minusBtn')
        }
    );
    view.show();
});
<select id="list" size="10" style="width: 15em"></select><br/>
<button id="plusBtn">  +  </button>
<button id="minusBtn">  -  </button>

分享到:
评论

相关推荐

    jquery-mvc.rar_The Client_jquery mvc_jquery.Controller_jquerymvc

    CorMVC stands for: Client-Only-Required 一个javascript的MVC框架 Model-View-Controller, and is my laboratory experiment in application architecture held completely seperate from server-side ...

    Net实战商用源码---ASP.NET MVC多用户博客源码

    它结合了ASP.NET 的功能强大的功能、Model-View-Controller (MVC) 设计模式以及对测试驱动开发(TDD) 的支持,为开发者提供了更灵活的开发环境。在“Net实战商用源码---ASP.NET MVC多用户博客源码”中,我们可以深入...

    14-Model-View-Controller-Tech-Blog

    **在"14-Model-View-Controller-Tech-Blog"项目中,可能包含对MVC模式的深入讨论,如何在JavaScript环境中应用MVC,以及可能的案例分析和最佳实践。通过学习这个项目,开发者可以提升对于前端架构的理解,掌握如何...

    cat-meows-simple-mvc:Javascript中的Model View Controller模式非常简单的示例

    **猫叫声:JavaScript中的Model-View-Controller模式详解** 在软件开发中,Model-View-Controller(MVC)模式是一种广泛应用于创建用户界面的设计模式,它将应用程序的业务逻辑、数据处理和用户交互分离开来,提高...

    购物网站-web-oracle-mvc

    1. **MVC架构**:MVC模式将应用程序分为三个主要部分——模型(Model)负责数据处理,视图(View)负责显示用户界面,控制器(Controller)处理用户输入并协调模型和视图。这种分离使得代码结构清晰,易于测试和维护...

    englishroom-final-Realeas-1.rar_MVC 聊天_聊天室 j2ee

    本项目——"englishroom-final-Realeas-1.rar",是一个利用J2EE技术实现的聊天室应用,它采用经典的Model-View-Controller(MVC)设计模式,旨在提供一个稳定、高效的实时通信环境。 首先,我们要理解MVC架构的核心...

    Angle-3.4-mvc5-angular

    2. **MVC5**:这是一个基于.NET Framework的Microsoft开发的Web应用框架,全称为Model-View-Controller。它将应用程序分为模型、视图和控制器三个部分,提高了代码的组织性和可测试性。在MVC5中,开发者可以利用ASP...

    spring mvc

    在Spring MVC中,Model代表数据模型,View负责展示数据,Controller处理用户请求并协调Model和View。这个框架的核心设计思想是模型-视图-控制器(MVC)架构模式,旨在实现业务逻辑与用户界面的分离,提高代码的可...

    viper-plugin-jade-mvc:viper-plugin-jade-mvc

    【viper-plugin-jade-mvc】是一个专门为JavaScript开发的插件,主要针对使用Jade(现在被称为Pug)模板引擎的MVC(Model-View-Controller)架构。这个插件致力于提升开发者的效率,简化在Viper框架下使用Jade进行视...

    26 MVC、MVP、MVVM.pdf

    JavaScript 设计模式精讲中,我们探讨了三种重要的软件架构模式:MVC(Model-View-Controller)、MVP(Model-View-Presenter)以及MVVM(Model-View-ViewModel)。这些模式广泛应用于前端开发,特别是在JavaScript...

    MVC模板解决方案 VS2008里面没有MVC模板 添加view和Controller时没有模板

    然而,对于一些较旧的版本,如VS2008,可能并未内置对Model-View-Controller(MVC)框架的支持。MVC是一种设计模式,常用于构建Web应用程序,它将业务逻辑、数据和用户界面分离,使得代码更易于维护和扩展。 标题...

    Programming Microsoft ASP.NET MVC 3rd Edition

    Web development expert Dino Esposito takes you through the web framework’s Model-View-Controller (MVC) design model, and covers the tools you need to cleanly separate business logic from the user ...

    angle-admin-v3.5.1(mvc5-angularjs版)

    ASP.NET MVC5是微软推出的一款开源Web应用程序框架,它基于Model-View-Controller(MVC)设计模式。MVC模式将应用程序分为三个主要部分:模型(Model)、视图(View)和控制器(Controller),这有助于实现更好的...

    MVC controller调用js源码

    首先,让我们理解MVC(Model-View-Controller)模式。MVC是一种设计模式,它将应用程序的业务逻辑、用户界面和数据模型分离。在ASP.NET MVC中,Controller是处理HTTP请求并决定如何响应的组件,View负责呈现数据,而...

    Angle-3.4-mvc5-jquery

    MVC(Model-View-Controller)模式是它的核心设计思想,它将应用逻辑分为三个部分:模型(Model)负责数据处理,视图(View)负责展示,控制器(Controller)处理用户请求并协调模型和视图。 2. jQuery: jQuery ...

    Pro Vue.js 2

    You will work with the power of the Model-View-Controller (MVC) pattern on the client, creating a strong foundation for complex and rich web apps. Best-selling author Adam Freeman explains how to ...

    基于PHP的AMP-PHP WEB应用开发MVC框架.zip

    MVC是一种软件设计模式,将业务逻辑(Model)、用户界面(View)和控制逻辑(Controller)分离,使代码结构清晰,易于维护。在AMP-PHP框架中,Model负责处理数据,View负责展示,Controller负责接收用户请求并调用...

    Programming Microsoft ASP.NET MVC, 3rd Edition

    Web development expert Dino Esposito takes you through the web framework’s Model-View-Controller (MVC) design model, and covers the tools you need to cleanly separate business logic from the user ...

    angle-admin-v3.5.1(mvc5-jquery版)

    ASP.NET MVC(Model-View-Controller)是一种用于构建可测试、高性能的Web应用程序的开源框架。它采用了MVC设计模式,将应用程序逻辑分为模型、视图和控制器三个部分,使得代码结构清晰,易于维护。MVC5是该框架的一...

    基于MVC的JavaScript Web富应用开发(完整版)

    MVC模式最早应用于桌面软件开发,现在已广泛应用于Web开发,尤其是JavaScript应用中,它将应用逻辑分为了三个主要部分:模型(Model)、视图(View)和控制器(Controller),使得代码结构清晰,易于维护。...

Global site tag (gtag.js) - Google Analytics