Home > Web Front-end > JS Tutorial > Understanding the MVC pattern in javascript_javascript tips

Understanding the MVC pattern in javascript_javascript tips

WBOY
Release: 2016-05-16 15:17:03
Original
1280 people have browsed it

MVC pattern is a software architecture pattern in software engineering. The software pattern is generally divided into three parts, Model + View + Controller;

Model: The model is used to encapsulate data related to the business logic of the application and methods for data processing. Models have direct access to the 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 operated.

View: The most important thing of the view layer is to monitor the data changes on the model layer and update the html page in real time. Of course, it also includes the registration of some events or ajax request operations (publishing events), which are all done in the view layer.

Controller: The controller receives the user's operation, the most important thing is to subscribe to the events of the view layer, and then call the model or view to complete the user's operation; for example: when an event is triggered on the page, the controller does not output anything and responds The page does no processing; it just receives the request and decides which method in the model to call to handle the request, and then determines which method in the view to call to display the returned data.

Let’s implement a simple drop-down box control, which we can add and delete as shown in the figure below:

The code is as follows:

/*
 模型用于封装与应用程序的业务逻辑相关的数据以及对数据处理的方法。模型有对数据直接访问的权利。
 模型不依赖 "视图" 和 "控制器", 也就是说 模型它不关心页面如何显示及如何被操作.
*/
function Mode(elems) {
  // 所有元素
  this._elems = elems;
 
  // 被选中元素的索引
  this._selectedIndex = -1;
 
  // 增加一项
  this.itemAdd = new Event(this);
 
  // 删除一项
  this.itemRemoved = new Event(this);
 
  this.selectedIndexChanged = new Event(this);
}
 
Mode.prototype = {
 
  constructor: 'Mode',
 
  // 获取所有的项
  getItems: function(){
    return [].concat(this._elems);
  },
  // 增加一项
  addItem: function(elem) {
    this._elems.push(elem);
    this.itemAdd.notify({elem:elem});
  },
  // 删除一项
  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});
  }
};
/*
 下面是观察者模式类,它又叫发布---订阅模式;它定义了对象间的一种一对多的关系,
 让多个观察者对象同时监听某一个主题对象,当一个对象发生改变时,所有依赖于它的对象都将得到通知。
*/
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._observer,objs);
    }
  }
};
 
/*
 * 视图显示模型数据,并触发UI事件。
 */
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;
 
  // 绑定模型监听器
  this._model.itemAdd.attach(function(){
    that.rebuildList();
  });
  this._model.itemRemoved.attach(function(){
    that.rebuildList();
  });
 
  // 将监听器绑定到HTML控件上
  this._elements.list.change(function(e){
    that.listModified.notify({index: e.target.selectedIndex});
  });
  // 添加按钮绑定事件
  this._elements.addButton.click(function(e){
    that.addButtonClicked.notify();
  });
  // 删除按钮绑定事件
  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);
  }
};
/*
 控制器响应用户操作,调用模型上的变化函数
 负责转发请求,对请求进行处理
*/
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);
  }
};
Copy after login

The HTML code is as follows:

<select id="list" size="10" style="width: 10rem">select>br/>
<button id="plusBtn"> + button>
<button id="minusBtn"> - button>
Copy after login

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();
});
Copy after login

The code analysis is as follows:

Let’s first analyze what kind of functions we want to achieve. Basic functionsare:

A drop-down box that allows the user to add an item and delete an item after selecting it through user input operations;
Of course, the event for the user to switch to that item is also added;

For example, when we add a piece of data now, add a listening event on the view layer, as shown in the following code:

// 添加按钮绑定事件
this._elements.addButton.click(function(e){
  that.addButtonClicked.notify();
});
Copy after login

Then call the notify method in the observer class Event (publish an event) that.addButtonClicked.notify(); As we all know, the observer mode is also called the publish-subscribe mode, allowing multiple observer objects to monitor a certain event at the same time. Theme object, when a theme object changes, all objects that depend on it will be notified;
Therefore, in the control layer (Controller) we can use the following code to monitor the publisher:

this._view.addButtonClicked.attach(function(){
  that.addItem();
});
Copy after login

Then call its own method addItem(); the code is as follows:

addItem: function(){
  var item = window.prompt('Add item:', '');
  if (item) {
    this._model.addItem(item);
  }
}
Copy after login

Call the method addItem() of the model layer (model); insert a piece of data into the select box; the code of the addItem() method of the model (model layer) is as follows:

// 增加一项
addItem: function(elem) {
  this._elems.push(elem);
  this.itemAdd.notify({elem:elem});
},
Copy after login

The above code adds an item, publishes a message through this.itemAdd, and then monitors the message through the following code on the view layer (View); the code is as follows:

// 绑定模型监听器
this._model.itemAdd.attach(function(){
   that.rebuildList();
});
Copy after login

After finally monitoring the data on the model (Model), it promptly calls its own method rebuildList() to update the data on the page;

The model layer (Model) is mainly responsible for business data encapsulation operations. The view layer (View) mainly publishes event operations and monitors data on the model layer. If the data on the model layer changes, it will update the page operation in time and finally display it on the page. The control layer (Controller) mainly monitors the view layer (View). event, call the method of the model layer (Model) to update the data on the model. After the model layer data is updated, a message will be published. Finally, the view layer (View) updates the page by monitoring the data changes of the model layer (Model). Display; The above is the basic process of MVC.
Advantages of MVC:
  1. Low coupling: The view layer and business layer are separated. If the display on the page changes, it can be changed directly in the view layer without touching the model layer and control The code on the layer; that is, the view layer, model layer and control layer
Already separated; so it's easy to change the data layer and business rules of the application layer.
​​   2. Maintainability: Separating the view layer and business logic layer also makes WEB applications easier to maintain and modify.
Disadvantages of MVC:
Personally I think it is suitable for large projects, and it is not suitable for small and medium -sized projects, because to achieve a simple addition, deletion and modification operation, only a little JS code is required, but the amount of MVC mode code has increased significantly.
The cost of learning will also increase. Of course, it would be better if you use some encapsulated MVC libraries or frameworks.

The above is a detailed analysis of the advantages and disadvantages of the MVC pattern implementation method in JavaScript. I hope it will be helpful to everyone's learning.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template