Some suggestions for JavaScript client application Programming _ Basics

Source: Internet
Author: User
Tags extend

As you may have noticed, more and more Web applications have become more complex in recent times, with the focus shifting slowly from the server to the client. Is this a normal trend? I do not know. The discussion of support and opponents is like talking about who the resurrection is better than Christmas. It's hard to say which side of the argument is absolutely right. Therefore, this article will not discuss which side is right, but I still try to explain the use of well-known object-oriented programming may be able to successfully solve some of the problems in client programming.

Examples of code that is not very canonical

To take into account the response of an application and the user experience, we create complex code that continues to grow, and the code becomes difficult to understand and maintain. You can easily think of a JavaScript application code that constructs a client without any framework and following rules:

$ (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 (");}
      });
   }
);

Maintaining this type of code will be difficult. Because this short piece of code is associated with many places: it controls a lot of events (sites, users, network events), it handles the user's action events, resolves the replies returned by the server, and generates HTML code. Someone might say, "Yes, you're right, but what if this isn't a client page application?" This is at best an example of excessive use of the jquery class library "-not very convincing, because it is well known that code that is easy to maintain and carefully designed is very important. In particular, many tools or frameworks are dedicated to keeping code available so that we can easily test, maintain, reuse, and extend it.

What is MVC?

talked about here. We can benefit from those 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 the two, which is hard to distinguish. That's why most JavaScript frameworks are based on mv*.

Changing the method may provide the organization and architecture of the client in the project, which makes the code easy to maintain over a long period of time, even if the refactoring of the already existing code becomes relatively easy. Knowing how he works and the answers to the following questions is something that needs to be remembered.

    • What types of data do I have in my application? -model
    • What should users see? -view
    • Who is the program that interacts with the user? -controller

Refactoring code with the MVC framework

What is the benefit of MVC refactoring code?

    • Unlock Dom and Ajax dependencies
    • The code has a better structure and is easier to test.
    • Remove the extra code from $ (document). Ready (), leaving only the section that uses model to create links.

Let's use some simple steps to refactor a typical block of code
Step 1: Create the View and move the AJAX request

We started to lift the DOM and Ajax dependencies. Using the Prototypes builder, the pattern creates the ' Animals ' object and adds an ' add ' method. Create View ' Newanimalview ' at the same time and add methods ' Addanimal ', ' appendanimal ', ' 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 (da
       Ta.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.

This example, the use of the MVC framework is the key. We will use event mechanisms that allow us to combine and trigger custom events. Therefore, we create new "Animalsview" and "Newanimalview" and give them different responsibilities for displaying animals. Using events to differentiate responsibilities is very simple. If you pass responsibilities between methods and events, as follows:

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: Pass the data structure to the core framework

Finally, the most important step, we 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});
}); 

Summarize

What have we achieved? We work on a high level of abstraction. Code maintenance, refactoring, and scaling become easier. We have greatly optimized the results of the code, isn't it fascinating? That's great. However, I may have to throw cold water on you, even if the best framework, the development of the code is still fragile and difficult to maintain. So if you think it's wrong to use a better mv* framework to solve all the code problems. Remember that the second step in the refactoring process is that the code becomes much better, and we don't use the main components of the framework.

Remember that the mv* framework is good for this, but all focus on ' how ' to develop an application that lets the program developer head decide ' What '. A supplement to each framework, especially when the project's domain is complex, will be the domain-driven design approach, which will focus more on the following aspects: "What", a process of translating requirements into real products. However, this is another topic that we are going to discuss.

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.