Some Suggestions on JavaScript client application programming, javascript Application Programming

Source: Internet
Author: User

Some Suggestions on JavaScript client application programming, javascript Application Programming

You may have noticed that more and more Web applications have become more complex recently, and the focus is gradually shifting from the server to the client. Is this a normal trend? I don't know. The discussion of support and opponents is just like discussing Which of the following is better for the resurrection and Christmas; it is hard to say which side of the view is completely correct. Therefore, this article will not discuss which one is right. However, I still try to explain that using object-oriented programming, which is well known, may successfully solve some problems in client programming.

Example of nonstandard code

In order to take into account the response and user experience of an application, we have created a constantly growing complex code that becomes hard to understand and maintain. You can easily think that the JavaScript application code for building a client without any architecture or rules will look like this:
 

$(function(){  $('#form').submit(function(e) {    e.preventDefault();     $.ajax({      url: '/animals',      type: 'POST',      dataType: 'json',      data: { text: $('#new-animal').find('textarea').val() },      success: function(data) {        $('#animals').append('<li>' + data.text + '</li>');        $('#new-animal').find('textarea').val('');      }     });   });});

It will be difficult to maintain this type of code. This short piece of code is associated with many places: it controls many events (sites, users, and network events) and processes user operation events, parse the response returned by the server and generate HTML code. Some people may say, "Yes, you are right, but if this is not a single-page client application? This can be regarded as an example of over-using jQuery class libraries at most. It is not very convincing because it is well known that easy-to-maintain and well-designed code is very important. In particular, many tools or frameworks are designed to keep code available so that we can test, maintain, reuse, and expand it more easily.

What is MVC?

Here. We can benefit from JavaScript frameworks based on MVC, but most of these frameworks do not use MVC, and are equivalent to a combination of Model and Videw, Or something between two, this is difficult to distinguish. That's why most Javascript frameworks are based on music videos *.

The change method may provide the Organization and architecture of the client in the project, which makes the code easy to maintain for a long time, even if the existing code is restructured. Knowing how he works and the answers to the following questions must be remembered.

  • What types of data does my application have? -Model
  • What Should users see? -View
  • Who is the program that interacts with the user? -Controller

Code reconstruction using MVC Framework

What are the benefits of using MVC to refactor code?

  • Remove DOM and Ajax Dependencies
  • The Code has a better structure and is easier to test.
  • Remove unnecessary code from $ (document). ready (), leaving only the part for creating Links using Model.

Let's use some simple steps to reconstruct a typical code block
Step 1: Create a view and move the Ajax request

We started to remove DOM and Ajax dependencies. use the prototypes builder to create the 'animal' object and add an 'add' method. create a view 'newanimalview' and add methods 'addanimal ', 'appendorigin', and 'clearinput '.

The Code is as follows:
 

var Animals = function() {}; Animals.prototype.add = function (options) {   $.ajax({     url: '/animals',     type: 'POST',     dataType: 'json',     data: { text: options.text },     success: options.success   });};  var NewAnimalView = function (options) {  this.animals = options.animals;  var add = $.proxy(this.addAnimal, this);  $('# form').submit(add); };  NewAnimalView.prototype.addAnimal = function(e) {   e.preventDefault();   var self = this;    this.animals.add({     text: $('#new-animal textarea').val(),     success: function(data) {       self.appendAnimal (data.text);       self.clearInput();          }   }); }; NewAnimalView.prototype.appendAnimal = function(text) {  $('#animals ul').append('<li>' + data.text + '</li>');};NewAnimalView.prototype.clearInput = function() {  $('#new-animal textarea').val('');};  $(document).ready(function() {   var animals = new Animals();   new NewAnimalView({ animals: animals }); });

Step 2: Use the event to remove dependencies.

In this example, using the MVC framework is critical. We will use the event mechanism, which allows us to combine and trigger custom events. therefore, we create new "AnimalsView" and "NewAnimalView" and assign them different responsibilities for displaying animals. It is very easy to use events to differentiate responsibilities. If you transfer responsibilities between methods and events, as shown below:
 

var events = _.clone(Backbone.Events);var Animals = function() {}; Animals.prototype.add = function(text) {   $.ajax({     url: '/animals',     type: 'POST',     dataType: 'json',     data: { text: text },     success: function(data) {      events.trigger('animal:add', data.text);     }   });}; var NewAnimalView = function(options) {  this.animals = options.animals;  events.on('animal:add', this.clearAnimal, this);  var add = $.proxy(this.addAnimal, this);  $('# form').submit(add); }; NewAnimalView.prototype.addAnimal = function(e) {   e.preventDefault();   this.animals.add($('#new-animal textarea').val()); }; NewAnimalView.prototype.clearInput = function() {  $('#new-animal textarea').val('');}; var AnimalsView = function() {  events.on('animal:add', this.appendAnimal, this);}; AnimalsView.prototype.appendAnimal = function(text) {  $('#animals ul').append('<li>' + data.text + '</li>');}; $(document).ready(function() {   var animals = new Animals();   new NewAnimalView({ animals: animals });   new AnimalsView();});

Step 3: transfer the data structure to the core framework

Finally, the most important step is to use: models, views and collections.
 

var Animal = Backbone.Model.extend({  url: '/animals'}); var Animals = Backbone.Collection.extend({  model: Animal}); var AnimalsView = Backbone.View.extend({  initialize: function() {    this.collection.on('add', this.appendAnimal, this);  },   appendAnimal: function(animal) {    this.$('ul').append('<li>' + animal.escape('text') + '</li>');  }});  var NewAnimalView = Backbone.View.extend({  events: {    'submit form': 'addAnimal'  },   initialize: function() {    this.collection.on('add', this.clearInput, this);  },   addAnimal: function(e) {    e.preventDefault();    this.collection.create({ text: this.$('textarea').val() });  },   clearInput: function() {    this.$('textarea').val('');  }}); $(document).ready(function() {  var animals = new Animals();  new NewAnimalView({ el: $('#new-animal'), collection: animals });  new AnimalsView({ el: $('#animals'), collection: animals });});

Summary

What have we achieved? We work on high abstraction. Code maintenance, refactoring, and expansion become easier. We have greatly optimized the Code results. Is it fascinating? Great. However, I may leave it hard for you. Even with the best framework, the developed code is still fragile and difficult to maintain. Therefore, if you think that using a better MV * framework can solve all the code problems, it is wrong. Remember that in the refactoring process, after the second step, the code will become much better and we will not use the main components of the framework.

Remember that the MV * framework is good, but all the attention is on 'who' to develop an application, which allows the developer to determine 'wh' in the header '. A supplement to each framework, especially when the project Domain is very complex, it will be a Domain-driven design method, which will be more concerned with the following aspects: "what ", the process of converting requirements into real products. However, this is another topic to be discussed.

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.