Understanding the MVC pattern in JavaScript _javascript techniques

Source: Internet
Author: User

MVC pattern is a software architecture pattern in software engineering, which divides software pattern into three parts, model + view (view) + controller (Controller);

Model: models are used to encapsulate data related to the business logic of an application and methods of data processing. The model has the right to direct access to data. The model does not rely on "view" and "Controller", which means that the model does not care about how the page is displayed and how it is manipulated.

Views: The main thing in the view layer is to listen for data changes on the model layer and update the HTML page in real time. The registration of events, or the AJAX request operations (publishing events), are also included in the view layer.

Controller: The controller receives the user's action, the most important is to subscribe to the view layer of the event, and then call the model or view to complete the user's operation, such as: When the page triggers an event, the controller does not output anything and the page to do any processing; It simply receives the request and decides to call the method in the model to process the request, and then determines the method that is invoked in that view to display the returned data.

Let's implement a simple Drop-down box control, which we can do with additions and deletions, as shown in the following figure:

The code is as follows:

The/* model is used to encapsulate data related to the business logic of the application and methods for data processing.
 The model has the right to direct access to data.
The model does not rely on "view" and "Controller", which means that the model does not care about how the page is displayed and how it is manipulated.
 
  */function Mode (elems) {//all elements this._elems = Elems;
 
  The index of the selected element this._selectedindex =-1;
 
  Add a this.itemadd = new Event (this);
 
  Deletes a this.itemremoved = new Event (this);
this.selectedindexchanged = new Event (this);
  } Mode.prototype = {constructor: ' Mode ',//Get all Items getitems:function () {return [].concat (This._elems)]
    },//Add a additem:function (elem) {This._elems.push (elem);
  This.itemAdd.notify ({Elem:elem});
    },///delete a removeitem:function (index) {var item = This._elems[index];
    This._elems.splice (index,1);
 
    This.itemRemoved.notify ({elem: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});
}
};
/* Below is the Observer pattern class, which is also called the Publish---subscription mode; it defines a one-to-many relationship between objects, allowing multiple observer objects to simultaneously listen to a Subject object, and when an object changes, all objects that depend on it are notified.
  * * Function Event (Observer) {THIS._OBSERVER = observer;
This._listeners = [];
  } Event.prototype = {constaructor: ' Event ', attach:function (listeners) {This._listeners.push (listeners); }, Notify:function (OBJS) {for (var i = 0,ilen = This._listeners.length i) {this._listeners[i] (this._observe
    R,OBJS);
 
}
  }
};
 /* View displays model data and triggers UI events.
  * * Function View (model,elements) {This._model = model;
 
  This._elements = elements;
  this.listmodified = new Event (this);
  this.addbuttonclicked = new Event (this);
  this.delbuttonclicked = new Event (this);
 
  var that = this;
  Binding model Listener This._model.itemadd.attach (function () {that.rebuildlist ();
  });
  This._model.itemremoved.attach (function () {that.rebuildlist ();
 
  });
Bind the listener to the HTML control This._elements.list.change (function (e) {    That.listModified.notify ({index:e.target.selectedindex});
  });
  Add button binding event This._elements.addbutton.click (function (e) {that.addButtonClicked.notify ();
  });
  Delete button binding event This._elements.delbutton.click (function (e) {that.delButtonClicked.notify ();
});
  } View.prototype = {constructor: ' View ', show:function () {this.rebuildlist ();
    }, Rebuildlist:function () {var list = this._elements.list, items, key;
    List.html ("");
    Items = This._model.getitems ();
      For (key in items) {if (Items.hasownproperty (key)) {list.append (' +items[key]+ ');
  } this._model.setselectedindex (-1);
}
};
  /* Controller in response to user action, call the change function on the model is responsible for forwarding requests, processing the request * * function Controller (model,view) {This._model = model;
  This._view = view;
 
  var that = this;
  This._view.listmodified.attach (function (Sender,args) {that.updateselected (args.index);
  });
  This._view.addbuttonclicked.attach (function () {That.additem ();
  }); This._view.Delbuttonclicked.attach (function () {That.delitem ();
});  } Controller.prototype = {constructor: ' Controller ', additem:function () {var item = window.prompt (' ADD item: ',
    '');
    if (item) {This._model.additem (item);
    }, Delitem:function () {var index = This._model.getselectedindex ();
    if (index!==-1) {This._model.removeitem (index);
  }, Updateselected:function (index) {this._model.setselectedindex (index);
 }
};

The HTML code is as follows:

<select id= "List" size= "ten" style= "Width:10rem" >select>br/>
<button id= "plusbtn" > + button>
<button id= "minusbtn" >-button>

The page initialization code is as follows:

$ (function () {
  var model = new Mode ([' PHP ', ' JavaScript ']),
   view = new View (model, {
    ' list ': $ (' #list '), 
   
     ' AddButton ': $ (' #plusBtn '), 
    ' Delbutton ': $ (' #minusBtn ')
    }),
    controller = new Controller (model, view);    
    view.show ();
});

   

Code analysis is as follows:

First analysis of what we are to achieve what kind of function, the basic functions are:

A drop-down box, the user input through the operation to achieve a user to add a and the user selected after the deletion of a function;
Of course, also added the user switch to that item of events;

For example, when we are adding a piece of data, we add a listener event to the view layer, as follows:

Add button binding event
This._elements.addbutton.click (function (e) {
  that.addButtonClicked.notify ();
});

Then call the method notify in the Observer class event (publish an event) that.addButtonClicked.notify (); As we all know, the observer pattern is also called the Publish-subscribe model, allowing multiple observer objects to simultaneously listen to a Subject object, When a Subject object changes, all the objects that depend on it will be notified;
So in the control layer (Controller) we can listen to the Publisher using the following code:

This._view.addbuttonclicked.attach (function () {
  that.additem ();
});

It then calls its own method AddItem (), and the code is as follows:

Additem:function () {
  var item = window.prompt (' ADD item: ', ');
  if (item) {
    This._model.additem (item);
  }
}

Call the model Layer method additem (); Insert a piece of data into the Select box; the AddItem () method code for model layer is as follows:

Add a
additem:function (elem) {
  this._elems.push (elem);
  This.itemAdd.notify ({Elem:elem});

After adding one item to the code, post a message via This.itemadd, and then listen to the message on the view layer by following the code below:

Binding Model Listener
This._model.itemadd.attach (function () {
   that.rebuildlist ();
});

Finally monitor the model on the data changes, timely call their own methods Rebuildlist () to update the data on the page;

Model layer is mainly to do business data encapsulation operations. The view layer mainly publishes event operations and listens to the data on the model layer, and if there is data change on the model layer, update the page operation in time, and finally show it to the page, the control layer (Controller) mainly listens for the event of view, and calls the model layer. method to update the data on the model, the model layer data update, will post a message out, the last view layer (views) by listening to the model layer of data changes, to update the page display; As above is the basic process of MVC.
Advantages of MVC:
1. Low coupling: view layer and business layer separated, if the page display changes, directly in the view layer changes can not move the model layer and the control layer code; That is, the view layer and the model layer and the control layer
has been separated, so it is easy to change the application layer's data layer and business rules.
2. maintainability: Separating the view layer and the business Logic layer also makes Web applications easier to maintain and modify.
Disadvantages of MVC:
Personally feel suitable for large projects, for small and medium-sized projects is not suitable, because to achieve a simple addition and deletion of the operation, only need a little bit of JS code, but the MVC pattern code volume significantly increased.
The cost of learning is also increased, of course, if you use some of the encapsulated MVC Library or framework of the good.

The above is about JavaScript in the MVC pattern implementation method, advantages and disadvantages of the detailed analysis, I hope to help you learn.

Related Article

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.