JS Simple notation

Source: Internet
Author: User
Tags event listener mathematical functions

I've been writing JavaScript code for a long time, and I can't remember what era it started. I am very excited about what JavaScript has achieved in recent years, and I am fortunate to have benefited from these achievements. I've written a lot of articles, chapters, and a book devoted to it, but I can still find some new knowledge about the language. The following description is the past that I could not help but send out "Ah!" "The exclamation of programming skills, these tips you should try now, instead of waiting for some time in the future to find them by chance.

Concise notation

One of my favorite things in JavaScript is the shorthand method for generating objects and arrays. In the past, if you wanted to create an object, you needed this:

1 var car = new Object (), 2 car.colour = ' red '; 3 Car.wheels = 4;4 car.hubcaps = ' spinning '; 5 car.age = 4;

The following writing can achieve the same effect:

1 var car = {2 colour: ' Red ', 3 wheels:4,4 hubcaps: ' Spinning ', 5 age:46}

It's much simpler, you don't have to use the name of the object repeatedly. So car is defined, perhaps you will encounter invaliduserinsession problem, this only you will encounter when using IE, just remember a little, do not put a comma in front of the curly braces, you will not have trouble.

Another very handy shorthand is for arrays. The traditional way to define arrays is this:

1 var moviesthatneedbetterwriters = new Array (2 ' Transformers ', ' Transformers2 ', ' Avatar ', ' Indianajones 4 ' 3);

The abbreviated version is this:

1 var moviesthatneedbetterwriters = [2 ' Transformers ', ' Transformers2 ', ' Avatar ', ' Indianajones 4 ' 3];

For arrays, there is a problem here, in fact, there is no graph group function. But you'll often find that someone defines the car above, like this.

1 var car = new Array (); 2 car[' colour '] = ' red '; 3 car[' wheels '] = 4;4 car[' hubcaps '] = ' spinning '; 5 car[' age ' = 4;

arrays are not omnipotent; it is confusing to write them wrong. The graph group is actually the function of the object, and people confuse the two concepts.

Another very cool shorthand method is to use with ternary conditional notation. You don't have to write the following.

1 var direction;2 if (x < $) {3 Direction = 1;4} else {5 direction = -1;6}

... You can use the ternary conditional notation to simplify it:

1 var direction = x < 200? 1:-1;

When the condition is true, take the value after the question mark, otherwise take the value after the colon.

Storing data in JSON form

Before I found JSON, I used a variety of crazy methods to store data in JavaScript's intrinsic data types, such as arrays, strings, symbols that were easy to split, and other annoying things. After Douglas Crockford invented JSON, it all changed. Using JSON, you can use JavaScript's own functionality to store data in complex formats without the need for additional conversions that can be accessed directly. JSON is the abbreviation for "JavaScript Object Notation", which uses the two shorthand methods mentioned above. So, if you want to describe a band, you might write like this:

var band = {"Name": "The Red hot Chili Peppers", "members": ["{" "Name": "Anthony Kiedis", "role": "Leads vocals" 0 7},08 {"Name": "Michael ' Flea ' Balzary", "role": "Bass guitar, trumpet, backing vocals" one},12 {"name": "Chad Smith" , "Role": "Drums,percussion"},16 {"name": "John Frusciante", "role": "Lead Guitar"}20],21  "Year": "2009" 22}

You can use JSON directly in JavaScript to encapsulate it in a function, even as a return value for an API. We call this json-p, and many APIs use this form. You can call a data supply source and return the JSON-P data directly in the script code:

<div id= "Delicious" ></div><script>02 function delicious (o) {$ var out = ' <ul> '; ; i<o.length;i++) {= ' <li><a href= ' + o[i].u + ' "> ' +06 o[i].d + ' </a></li> ';}08 out + = ' </ul> '; document.getElementById (' delicious '). InnerHTML = out;10}11 </script>12 <script src= "http ://feeds.delicious.com/v2/json/codepo8/javascript?count=15&callback=delicious "></script>

This is the Web Service feature that is called by the Delicious Web site to get a list of the most recent unordered bookmarks in JSON format.

Basically, JSON is the lightest way to describe complex data structures, and it can be run in a browser. You can even run it in PHP with the Json_decode () function. One of the things that makes me wonder about JavaScript's own functions (math, Array, and string) is that when I look at math and string functions in JavaScript, I find that they can greatly simplify my programming work. Using them, you can eliminate complex cyclic processing and conditional judgments. For example, when I need to implement a function to find the largest number in a number array, I used to write this loop like this:

1 var numbers = [3,342,23,22,124];2 var max = 0;3 for (var i=0;i<numbers.length;i++) {4 if (Numbers[i] > Max) {5 max = n Umbers[i];6}7}8 alert (max);

We can do this without the need for loops:

1 var numbers = [3,342,23,22,124];2 numbers.sort (function (A, b) {return b-a}); 3 alert (numbers[0]);

It is important to note that you cannot sort () a numeric character array, because in this case it will only be sorted in alphabetical order. If you want to know more about the usage, you can read this good article about sort ().

Another interesting function is Math.max (). This function returns the largest number in the number in the argument:

1 Math.max (12,123,3,2,433,4); Returns 433

Because this function can verify the number and return the largest one, you can use it to test the browser's support for a feature:

1 var scrolltop=math.max (2 doc.documentelement.scrolltop,3 DOC.BODY.SCROLLTOP4);

This is used to solve the IE problem. You can get the scrolltop value of the current page, but depending on the DOCTYPE on the page, only one of these two properties will hold this value, and the other will be undefined, so you can get this number by using Math.max (). Reading this article will give you more knowledge about using mathematical functions to simplify JavaScript.

Another function that has a pair of very useful action strings is split () and join (). I think the most representative example would be to write a function that attaches a CSS style to the page element.

So, when you attach a CSS class to a page element, either it is the first CSS class of the element, or it already has some class, you need to add a space to the existing class, and then append the class. And when you want to get rid of this class, you also need to remove the space in front of this class (this is very important in the past, because some old browsers do not know the class that followed the space).

So, the original wording would be this:

1 function addclass (elm,newclass) {2 var c = elm.classname;3 Elm.classname = (c = = = ")? newclass:c+ ' +newclass;4}

You can use the split () and join () functions to automate this task:

1 function addclass (elm,newclass) {2 var classes = Elm.className.split ("); 3 Classes.push (Newclass); 4 Elm.classname = CLA Sses.join ("); 5}

This will ensure that all classes are separated by spaces, and that the class you want to append is exactly the last one.

Event delegation

Web applications are event-driven. I like event handling, and I especially like defining events myself. It allows you to expand your product without having to change the core code. There is a big problem (and it can be said to be a powerful performance) about the removal of events on the page. You can install an event listener on an element, and the event listener will begin to function. But there is no indication on the page that there is a listener. Because of this non-expressive problem (which in particular makes some novice headaches) and a "browser" like IE6, there are a variety of memory problems when listening to too many usage events, you have to admit that using event programming as little as possible is a smart idea.

Then the event delegation appeared.

When an event on an element on a page is triggered, and on the DOM inheritance, all child elements of the element can also receive this event, you can use an event handler on the parent element to process it instead of using an event listener on a bunch of individual child elements. What exactly does that mean? In this case, there are a lot of hyperlinks on the page, you don't want to use these links directly, you want to call this link through a function, the HTML code is:

1 

It is common practice to attach an event handler on each link by looping through these links:

01//Typical event handling example (function () {The var resources = document.getElementById (' resources '); var links = resources.getelement Sbytagname (' a '); var all = links.length;06 for (var i=0;i<all;i++) {//Attach a listener to each link08 Links[i].add EventListener (' click ', handler,false);};10 function Handler (e) {one var x = e.target;//Get the link that is clicked12 a Lert (x); E.preventdefault (); 14};15}) ();

We can also accomplish this task with an event handler:

(function () {The var resources = document.getElementById (' resources '); Resources.addeventlistener (' Click ', Handler , false), Handler (e) {var x = E.target;//Get the link tha06 if (x.nodename.tolowercase () = = = ' A ') {-Alert (' E Vent delegation: ' + x '; E.preventdefault (); 09}10};11}) ();

Because click events occur in these page elements, all you have to do is compare their nodeName to find the element that should respond to the event.

Disclaimer: The above-mentioned two examples of events, in all browsers can be run, in addition to IE6, on the IE6 you need to use an event model, rather than a simple standard implementation of the Web. This is why we recommend using some toolkits.

The benefit of this approach is not limited to reducing the number of event processors to one. You think, for example, you need to dynamically add more links to the link table. With the event delegate, you do not need to make any other changes, otherwise you will need to re-loop the link table and re-install the event handler for each link.

anonymous functions and modularity

The most annoying thing in JavaScript is that variables are not in use. Any variable, function, array, object, as long as it is not inside the function, is considered to be global, that is to say, the other script on this page can also access it, and can override it.

The solution is to put your variable inside an anonymous function and call it immediately after the definition is complete. For example, the following syntax will produce three global variables and two global functions:

1 var name = ' Chris '; 2 var age = ' $ '; 3 var status = ' single '; 4 function Createmember () {5//[...] 6}7 function Getmemberdetails () {8//[...] 3 ·

If there is a variable called status in other scripts on this page, the trouble arises. If we encapsulate them in a myapplication, the problem is solved:

The var myapplication = function () {The var name = ' Chris '; var = ' $ '; var status = ' single '; function Createmembe R () {06//[...] }08 function Getmemberdetails () {09//[...] 10}11} ();

However, there is no function outside of the function. If that's what you need, then it's okay. You can also omit the name of the function:

(function () {createmember var name = ' Chris '; var age = ' "," var status = ' single '; "function" {06//[...] }08 function Getmemberdetails () {09//[...] 10}11}) ();

If you want to use the inside of the function, you need to make some changes. To be able to access createmember () or getmemberdetails (), you need to turn them into MyApplication properties, exposing them to the outside world:

MyApplication var = function () {The var name = ' Chris '; var age = ' $ '; var status = ' single '; return{06 creatememb Er:function () {07//[...] },09 getmemberdetails:function () {10//[...] }12}13} (),//myapplication.createmember () and//myapplication.getmemberdetails () can be used.

This is called module mode or singleton. Douglas Crockford Many times talked about these, Yahoo user Interface Library YUI in this has a lot of use. But what makes me uncomfortable is that I need to change the sentence to make the functions and variables accessible to the outside world. What's more, I need to add myapplication to this prefix when I call them. So, I don't like to do that, I prefer to simply give pointers to the elements that need to be accessible by the outside world. This simplifies the way outside calls are made:

The var myapplication = function () {The var name = ' Chris '; var = ' $ '; var status = ' single '; function Createmembe R () {06//[...] }08 function Getmemberdetails () {09//[...] Ten}11 return{12 create:createmember,13 get:getmemberdetails14}15} (); 16//Now written in Myapplication.get () and Myapplication.create () on the line.

I call this "revealing module pattern."

Configurable

Once I've posted the JavaScript code in this world, someone wants to change it, usually people want it to do something that it doesn't do-but usually it's not flexible enough to provide user-definable functionality. The workaround is to add a configuration item object to your script. I have written an in-depth article about JavaScript configuration item objects, and here are some of the key points:

    • In your script, add an object called configuration .
    • Inside this object, store all the things that people often change when they use this script:
      • CSS ID and class name;
      • The name of the button, sign and so on;
      • Values such as "Number of pictures per page", "Dimensions of image display";
      • locations, location, and language settings.
    • Returns this object as a common property to the user, so that the user can modify it to overwrite it.

Usually this is the last thing you need to do in your programming process. I concentrated on this in one example: "Five things to does to a script before handing it-to-the-next developer."

In fact, you want your code to be used in a way that makes people use it and make changes to their needs. If you do this, you will receive fewer emails from people complaining about your script that will tell you that someone has modified your script and that it works well.

Interacting with the background

One of the important things I've learned over the years of programming is that JavaScript is a great language for developing interface interactions, but if you're working with numbers or accessing data sources, it's a bit retwist.

Originally, I learned JavaScript as a replacement for Perl, because I hated the need to copy the code into the Cgi-bin folder for Perl to run. Later, I realized that I should use a background working language to deal with the main data, and not to let JavaScript do everything. More importantly, we have to consider security and language features.

If I visit a Web service, I can get the data into the json-p format, in the client browser I do a variety of data conversion, but when I have the server, I have more ways to transform the data, I can generate JSON or HTML-formatted data back to the client on the server side, as well as caching the data. If you know it beforehand and prepare for it, you will have long-term benefits and save a lot of headaches. Writing programs that apply to various browsers is a waste of time, use a toolkit!

When I first started web development, it was a long struggle to use document.all or use document.layers when I visited the page. I chose document.layers because I liked the idea that any layer was my own document (and I wrote too many document.write to generate the elements). Layer mode eventually failed, so I started using document.all. I was happy when Netscape 6 announced support for the DOM model only, but the user didn't really care. The user simply sees that this browser does not show what most browsers are capable of displaying properly-this is the problem with our coding. We write short-sighted code that only runs in the current environment, and unfortunately our operating environment is constantly changing.

I've wasted too much time dealing with issues that are compatible with various versions of various browsers. Being good at dealing with such problems provides me with a good job opportunity. But now we don't have to endure this pain.

Some toolkits, such as YUI, JQuery, and dojo, can help us deal with this kind of problem. They solve various browser problems by abstracting various interface implementations, such as incompatible versions, design flaws, and so on, freeing us from pain. Unless you want to test a beta version of the browser, do not add code to fix the bug in your browser, because you most likely when the browser has modified the problem, you forgot to delete your code.

On the other hand, full reliance on toolkits is also a short-sighted behavior. The toolkit can help you develop quickly, but you'll do the wrong thing if you don't understand JavaScript in depth.

JS Simple notation

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.