`
lmh2072005
  • 浏览: 111391 次
  • 性别: 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 ...

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

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

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

    ASP.NET MVC Framework Unleashed(Stephen Walther)

    Writing for professional programmers, Walther explains the crucial concepts that make the Model-View-Controller (MVC) development paradigm work so well and shows exactly how to apply them with the ASP...

    Developing Backbone.js Applications

    You'll learn how to create structured JavaScript applications, using Backbone's own flavor of model-view-controller (MVC) architecture. Start with the basics of MVC, SPA, and Backbone, then get your ...

    Developing backbone.js application

    You’ll learn how to create structured JavaScript applications, using Backbone’s own flavor of model-view-controller (MVC) architecture. Start with the basics of MVC, SPA, and Backbone, then get ...

    谈谈关于JavaScript 中的 MVC 模式

    原文:Model-View-Controller (MVC) with JavaScript作者:Alex@Net译文:JavaScript 的 MVC 模式译者:justjavac 本文介绍了模型-视图-控制器模式在 JavaScript 中的实现。 我喜欢 JavaScript,因为它是在世界上最...

    Pro Vue.js 2(pdf英文原版-2018版)

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

    backbone marionette js

    You'll learn how to create structured JavaScript applications, using Backbone's own flavor of model-view-controller (MVC) architecture. Start with the basics of MVC, SPA, and Backbone, then get your ...

    developing backbone js applications

    You'll learn how to create structured JavaScript applications, using Backbone's own flavor of model-view-controller (MVC) architecture. Start with the basics of MVC, SPA, and Backbone, then get your ...

    Apress.Pro.Vuejs.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 ...

    《AngularJS: Novice to Ninja》- 2017 英文原版

    Developed and maintained by Google, AngularJS brings the Model-View-Controller (MVC) pattern to JavaScript applications and provides a high quality foundation for building complex and powerful apps ...

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

    猫叫声 它是什么 这是一个Javascript中具有最小依赖关系的模型视图控制器模式的非常简单的示例。 演示

    gomvc-admin-lucultura:简单的MVC和API框架1.0.0

    src --controller --model --view srcApi --Apicontroller --Apimodel 在这个专案上: 仪表板管理员 权限=&gt;创建用户并添加路由权限。 从终端创建控制器,模型,视图。 具有特定角色的用户 用户可以修改个人...

    calculator:使用MVC模式的香草JavaScript计算器

    计算器使用Model-View-Controller(MVC)设计模式的香草JavaScript计算器。 如何运行:计算器上线后,将包含一个查看链接。模型描述管理数据,该数据将是计算器将评估并计算结果的数学表达式。执行计算用户的中缀...

    Porgramming ASP.NET MVC 4

    You’ll start by learning core concepts such as the Model-View-Controller architectural pattern, and then work your way toward advanced topics. The authors demonstrate ASP.NET MVC 4 best practices and...

    AngularJS Novice to Ninja

    Developed and maintained by Google, AngularJS brings the Model-View-Controller (MVC) pattern to JavaScript applications and provides a high quality foundation for building complex and powerful apps ...

    JavaScript-AngluarJs.pdf

    最为核心的是:MVC(Model–view–controller)、模块化、自动化双向数据绑定、语义化 标签、依赖注入等等。 AngularJS 是一个 JavaScript 框架。它是一个以 JavaScript 编写的库。它可通过 &lt;script&gt; 标签添加到 ...

Global site tag (gtag.js) - Google Analytics