Home > Web Front-end > JS Tutorial > A brief discussion on using MVC mode for JavaScript program development_javascript skills

A brief discussion on using MVC mode for JavaScript program development_javascript skills

WBOY
Release: 2016-05-16 15:32:47
Original
1443 people have browsed it

As front-end development is increasingly valued and the proportion of client code is increasing day by day, the question of how to apply the MVC pattern in JavaScript development seems to be mentioned all the time, so I would like to briefly talk about my views here. .

The basic idea of ​​the MVC pattern is to reduce coupling and simplify development by encapsulating an application into three parts: model, view and controller. It’s hollow to say this. Let’s take a look at an example:

<select id="selAnimal">
  <option value="cat">cat</option>
  <option value="fish">fish</option>
  <option value="bird">bird</option>
</select>
<p id="whatDoesThisAnimalDo"></p>

<script type="text/javascript">
document.getElementById('selAnimal').onchange = function() {
  var thisAnimalDoes;
  switch ( this.value ) {
    case 'cat':
      thisAnimalDoes = "cat meows";
      break;
    case 'fish':
      thisAnimalDoes = "fish swims";
      break;
    case 'bird':
      thisAnimalDoes = "bird flies";
      break;
    default:
      thisAnimalDoes = "wuff&#63;";
  }
  document.getElementById('whatDoesThisAnimalDo').innerHTML = thisAnimalDoes;
}
</script>

Copy after login

This small program will echo what the animal you select from the drop-down menu "selAnimal" can do to the web page. The above is code written without applying any design patterns or programming ideas. If we want to apply the MVC pattern here, what will the code look like?

<select id="selAnimal">
  <option value="cat">cat</option>
  <option value="fish">fish</option>
  <option value="bird">bird</option>
</select>
<p id="whatDoesThisAnimalDo"></p>

<script type="text/javascript">
// whatDoesAnimalDo 就是一个controller
var whatDoesAnimalDo = {
  // 选择视图
  start: function() {
    this.view.start();
  },
  // 将用户的操作映射到模型的更新上
  set: function(animalName) {
    this.model.setAnimal(animalName);
  },
};
// whatDoesAnimalDo的数据model
whatDoesAnimalDo.model = {
  // animal的数据
  animalDictionary: {
    cat: "meows",
    fish: "swims",
    bird: "flies"
  },
  // 当前的animal,也就是这个application的状态
  currentAnimal: null,
  // 数据模型负责业务逻辑和数据存储
  setAnimal: function(animalName) {
    this.currentAnimal = this.animalDictionary[animalName] &#63; animalName : null;
    this.onchange();
  },
  // 并且通知视图更新显示
  onchange: function() {
    whatDoesAnimalDo.view.update();
  },
  // 还需要响应视图对当前状态的查询
  getAnimalAction: function() {
    return this.currentAnimal &#63; this.currentAnimal + " " + this.animalDictionary[this.currentAnimal] : "wuff&#63;";
  }
};
// whatDoesAnimalDo的视图
whatDoesAnimalDo.view = {
  // 用户输入触发onchange事件
  start: function() {
    document.getElementById('selAnimal').onchange = this.onchange;
  },
  // 该事件将用户请求发送给控制器
  onchange: function() {
    whatDoesAnimalDo.set(document.getElementById('selAnimal').value);
  },
  // 视图更新显示的方法,其中视图会向model查询当前的状态,并将其显示给用户
  update: function() {
    document.getElementById('whatDoesThisAnimalDo').innerHTML = whatDoesAnimalDo.model.getAnimalAction();
  }
};
whatDoesAnimalDo.start();
</script>

Copy after login

...Suddenly the code became so exaggerated....
——Odu has not implemented the observer mode in it yet...
It's really not good.

This brings out the biggest criticism of the MVC pattern: applying the MVC pattern in a simple system will increase the complexity of the structure and reduce efficiency.

So I think that except for a few javascript controls, such as click-anywhere-to-edit datagrid/tree control, or rich text editors like FckEditor/tinyMCE that support custom plugins, which are very suitable for applying MVC, in most In a practical B/S system, as long as you follow the factory pattern in JavaScript development, you will benefit a lot. This is caused by the different nature of front-end development and back-end development. If you apply the MVC pattern in an ASP.net or JSP project, the SDK will more or less automatically generate some view and controller code. But what about JavaScript - JavaScript doesn't even have a useful SDK. Although there are many mature frameworks, it will ultimately increase the amount of development greatly.

Compared with the amount of development, what is more troublesome is the issue of efficiency. Intercommunication between the three layers is additional overhead. For the server side, the overhead caused by these communications is almost negligible. But for a relatively inefficient language like javascript, a few more calls and event listening will obviously reduce the performance. Moreover, because of the closure feature of javascript, memory leaks may occur accidentally. This is an authentic case of stealing the chicken but losing the rice...
Therefore, for JavaScript development, moderate development may be more important than applying the academic knowledge you have learned. After all, front-end development is based on solving practical problems, not for showing off skills. Of course, Dflying gg has a saying that "refactoring is everywhere" - if you feel that your own code is getting messier and more difficult to maintain, then you should consider whether you should use MVC to refactor it. Got it~

One more thing: Does the entire front-end development no longer need to use MVC? no no~ In fact, the entire front-end development is a big MVC architecture——

Model: Information in HTML/XHTML
View: Style sheet
Controller: EMAScripts and other scripts
Isn’t this the ultimate goal of web standards....

Therefore, it is always more important to grasp the structure of the entire front-end code than over-application of design models in JavaScript development!

However, there are also some excellent MVC frameworks. Gordon L. Hempton, a hacker and designer in Seattle, made a comparison. Here we pull them over to take a look:

1. Backbone.js - Advantages: strong community, strong momentum; Disadvantages: weak abstraction, many functions need to be added urgently.
2. SproutCore - Advantages: support for binding, reliable community, large number of features; Disadvantages: over-specification, difficult to decouple from unnecessary features.
3. Sammy.js - Advantages: easy to learn and easier to integrate with existing server applications; disadvantages: too simple to be used in large applications.
4. Spine.js - Advantages: lightweight, complete documentation; Disadvantages: Its core concept "spine" is an asynchronous user interface, which means that ideally the user interface will never be blocked , and this foundation is flawed.
5. Cappuccino - Pros: Large well-thought-out framework, good community, great inheritance model; Cons: Created by iOS developers, using JavaScript to simulate Objective-C.
6. Knockout.js - Advantages: Support for binding, complete documentation and tutorials; Disadvantages: Poor binding syntax, lack of unified view component hierarchy.
7. Javascript MVC - Advantages: reliable community; Disadvantages: poor string-based inheritance model, too close relationship between controller and view and lack of binding.
8. GWT (Google Web Toolkit) - Advantages: comprehensive framework, good community, reliable Java-based component inheritance model; Disadvantages: may not withstand the test of time, in addition, Java is on the client side The abstraction above is a bit clumsy.
9. Google Closure——Advantages: Very good component-based UI composition system. Disadvantages: Lack of UI binding support.
10. Ember.js - Advantages: Very rich template system, with composite views and UI binding; Disadvantages: It is relatively new and the documentation is not complete enough.
11. Angular.js - Advantages: It has good considerations for template scope and controller design, has a dependency injection system, and supports rich UI binding syntax. Disadvantages: The modularity of the code is not strong, and the modularity of the view is not enough.
12. Batman.js——Advantages: clear code, simple binding and persistence methods; disadvantages: singleton controller is used.

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