JavaScript MVC pattern (reprint)

Source: Internet
Author: User

This article describes the implementation of the model-view-controller pattern in JavaScript.

I like JavaScript because it is one of the most flexible languages in the world. In JavaScript, programmers can choose a programming style based on their tastes: process-oriented or object-oriented. If you're a heavy-taste, JavaScript can handle it: process-oriented, object-oriented, and use JavaScript developers can even use functional programming techniques.

My goal in this article is to write a simple JavaScript component to show you the power of JavaScript. The component is a list of editable items (select tags in html): The user can select an item and delete it, or add a new item to the list. The component will consist of three classes that correspond to the model-view-controller of the MVC design pattern.

This post is just a simple guide. If you want to use it in an actual project, you need to make the appropriate modifications. I believe you have everything you have to create and run JavaScript programs: Brains, hands, text editors (such as Notepad), browsers (like my favorite Chrome).

Since our code uses the MVC pattern, here's a brief introduction to this design pattern. The English name of the MVC pattern is model-view-controller pattern, which, by definition, consists of its main parts:

Model (), used to store data used in the program;

View, presenting the data in different representations;

Controller to update the model.

In Wikipedia's definition of the MVC architecture, it consists of the following three parts:

Model-The data model is used to encapsulate data related to the business logic of the application and how to handle the data. "Model" has the right to direct access to data. "Model" does not depend on "view" and "Controller", that is, the model does not care how it will be displayed or how it is manipulated.

View-The view layer is capable of achieving a purposeful display of data, usually a user interface element. There is generally no logic on the program in the view. MVC in a WEB application typically calls an HTML page that displays dynamic Data as a view.

Controller-handles and responds to events, typically user actions, and monitors changes on the model, then modifies 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 was very simple-it is stored a array property and selected item property; And here it is:

We will implement a data list component based on MVC, and items in the list can be selected and deleted. Therefore, the component model is very simple-it requires only two properties:

The array _items is used to store all the elements; the normal variable _selectedindex is used to store the selected element index

The code is as follows:

/** * model.   * * The model stores all elements and notifies the Observer (Observer) when the state changes. */   functionListmodel (items) { This. _items = items;//all elements     This. _selectedindex =-1;//index of selected element      This. itemAdded =NewEvent ( This);  This. itemremoved =NewEvent ( This);  This. SelectedIndexChanged =NewEvent ( This); } Listmodel.prototype={getItems:function () {          return[].concat ( This. _items); }, AddItem:function(item) { This. _items.push (item);  This. Itemadded.notify ({item:item}); }, Removeitemat:function(index) {varitem; 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) {varPreviousindex; Previousindex= This. _selectedindex;  This. _selectedindex =index;  This. Selectedindexchanged.notify ({previous:previousindex});  }  }; 

The Event is a simple class that implements the Observer pattern (Observer pattern):

functionEvent (sender) { This. _sender =Sender;  This. _listeners = []; } Event.prototype={attach:function(listener) { This. _listeners.push (listener); }, notify:function(args) {varindex;  for(index = 0; Index < This. _listeners.length; Index + = 1) {               This. _listeners[index] ( This. _sender, args);  }      }  }; 

The View class needs to define the controller class to interact with it. Although this task can have many different interfaces (interface), I prefer the simplest. I want my project to be in a ListBox control and two buttons underneath it: "Plus" button to add items, "minus" to delete selected items. The "select" feature provided by the component requires support for the native functionality of the Select control.

A View class is bound to a Controller class, where "... The controller handles user input events, usually through a registered callback function "(wikipedia.org).

The following are the View and Controller classes:

/** * view.   * * View displays model data and triggers UI events. * controllers are used to handle these user interaction events*/   functionListView (model, elements) { This. _model =model;  This. _elements =elements;  This. listmodified =NewEvent ( This);  This. addbuttonclicked =NewEvent ( This);  This. delbuttonclicked =NewEvent ( This); var_this = This; //Binding Model Listeners     This. _model.itemadded.attach (function() {_this.rebuildlist ();       });  This. _model.itemremoved.attach (function() {_this.rebuildlist ();       }); //to bind the listener to an HTML control     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 () {          varlist, items, key; List= This. _elements.list; List.html (‘‘); Items= This. _model.getitems ();  for(Keyinchitems) {              if(Items.hasownproperty (key)) {List.append ($ (' <option> ' + items[key] + ' </option> ')); }          }            This. _model.setselectedindex (-1);   }  }; /** * Controller.   * * The controller responds to user actions and invokes the change function on the model. */   functionListcontroller (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 () {          varitem = window.prompt (' ADD item: ', '); if(item) { This. _model.additem (item); }}, Delitem:function () {          varindex; Index= This. _model.getselectedindex (); if(Index!==-1) {               This. _model.removeitemat ( This. _model.getselectedindex ()); }}, updateselected:function(index) { This. _model.setselectedindex (index);  }  }; 

Of course, Model, View, and Controller classes should be instantiated.

The following is a complete code that uses this MVC:

 $ (function   () { var  model = new  Listmodel ([' PHP ', ' JavaScript '  = new   ListView (model, { ' list ': $ (' #list '  ' AddButton ': $ (' #      Plusbtn '  ' Delbutton ': $ (' #minusBtn ' ) }), Controller  = new   Listcontroller (              model, view);  View.show ();   });   <select id= "list" size= "style=" width:15em "></select><br/> <button id=" plusbtn "> + </button> <button id= "minusbtn" >-</button> 

Original link: http://justjavac.com/javascript/2012/12/14/model-view-controller-mvc-javascript.html

JavaScript MVC pattern (reprint)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.