7 JavaScript tricks you should have known

Source: Internet
Author: User
Tags event listener mathematical functions





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:4
6 	}


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 < 200){
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:


01 	var band = {
02	 	"name":"The Red Hot Chili Peppers",
03	 	"members":[
04		 	{
05		 	"name":"Anthony Kiedis",
06		 	"role":"lead vocals"
07		 	},
08 			{
09 			"name":"Michael ‘Flea‘ Balzary",
10 			"role":"bass guitar, trumpet, backing vocals"
11 			},
12 			{
13 			"name":"Chad Smith",
14 			"role":"drums,percussion"
15 			},
16		 	{
17 			"name":"John Frusciante",
18		 	"role":"Lead Guitar"
19		 	}
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:


01 	<div id="delicious"></div><script>
02 	function delicious(o){
03 		var out = ‘<ul>‘;
04	 	for(var i=0;i<o.length;i++){
05 			out += ‘<li><a href="‘ + o[i].u + ‘">‘ +
06 			o[i].d + ‘</a></li>‘;
07 		}
08 		out += ‘</ul>‘;
09 		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 = numbers[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.scrollTop
4 	);


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 = classes.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 	<h2>Great Web resources</h2>
2 	<ul id="resources">
3 	<li><a href="http://opera.com/wsc">Opera Web Standards Curriculum</a></li>
4 	<li><a href="http://sitepoint.com">Sitepoint</a></li>
5 	<li><a href="http://alistapart.com">A List Apart</a></li>
6 	<li><a href="http://yuiblog.com">YUI Blog</a></li>
7 	<li><a href="http://blameitonthevoices.com">Blame it on the voices</a></li>
8 	<li><a href="http://oddlyspecific.com">Oddly specific</a></li>
9 	</ul>


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


01 // Typical event handling example
02 (function(){
03 var resources = document.getElementById(‘resources‘);
04 var links = resources.getElementsByTagName(‘a‘);
05 var all = links.length;
06 for(var i=0;i<all;i++){
07 // Attach a listener to each link
08 links[i].addEventListener(‘click‘,handler,false);
09 };
10 function handler(e){
11 var x = e.target; // Get the link that was clicked
12 alert(x);
13 e.preventDefault();
14 };
15 })();


We can also accomplish this task with an event handler:


01 	(function(){
02 		var resources = document.getElementById(‘resources‘);
03 		resources.addEventListener(‘click‘,handler,false);
04 		function handler(e){
05		 	var x = e.target; // get the link tha
06 			if(x.nodeName.toLowerCase() === ‘a‘){
07 				alert(‘Event delegation:‘ + x);
08 				e.preventDefault();
09 			}
10 		};
11 	})();


Because click events happen in these page elements, all you have to do is compare their nodeNames to find the one that should respond to the event.

Disclaimer: The two examples of events mentioned above can be run in all browsers. Except for IE6, you need to use an event model on IE6 instead of the simple W3C standard implementation. That's why we recommend some toolkits.

The benefit of this approach is not limited to reducing multiple event handlers to one. Think about it, for example, you need to dynamically add more links to this linked list. After using the event delegate, you don't need to make any other changes; otherwise, you need to re-cycle 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 don't have scope. Any variable, function, array, object, as long as it is not inside the function, is considered global, which means that other scripts on this page can also access it, and override it.


1 	var name = ‘Chris‘;
2 	var age = ‘34‘;
3 	var status = ‘single‘;
4 	function createMember(){
5 	// [...]
6 	}
7 	function getMemberDetails(){
8 	// [...]
9 	}


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

If there is a variable called status in other scripts on this page, the trouble will appear. If we wrap them in a myApplication , the problem is solved:

01 	var myApplication = function(){
02 		var name = ‘Chris‘;
03 		var age = ‘34‘;
04 		var status = ‘single‘;
05 		function createMember(){
06 			// [...]
07 		}
08 		function getMemberDetails(){
09 			// [...]
10 		}
11 	}();




However, in this way, there is no function outside the function. If this is what you need, then you can. You can also omit the name of the function:


01 	(function(){
02 		var name = ‘Chris‘;
03 		var age = ‘34‘;
04 		var status = ‘single‘;
05 		function createMember(){
06 			// [...]
07 		}
08 		function getMemberDetails(){
09 			// [...]
10 		}
11 	})();


If you want to use something inside the function, you need to make some changes. In order to access createMember() or getMemberDetails() , you need to turn them into properties of myApplication and expose them to the outside world:


01 var myApplication = function(){
02 var name = ‘Chris’;
03 var age = ‘34’;
04 var status = ‘single‘;
05 return{
06 createMember:function(){
07 // [...]
08 },
09 getMemberDetails:function(){
10 // [...]
11 }
12 }
13 }();
14 //myApplication.createMember() and
15 //myApplication.getMemberDetails() is ready to use.


This is called module mode or singleton. Douglas Crockford talked about this many times, and there is a lot of use in the Yahoo User Interface Library YUI. But what makes me feel inconvenient is that I need to change the sentence to make functions and variables accessible to the outside world. What's more, I also need to add the prefix myApplication when calling. So, I don't like to do this, I prefer to simply export pointers to elements that need to be accessed by the outside world. After doing this, it simplifies the way the outside call is written:


01 var myApplication = function(){
02 var name = ‘Chris’;
03 var age = ‘34’;
04 var status = ‘single‘;
05 function createMember(){
06 // [...]
07 }
08 function getMemberDetails(){
09 // [...]
10 }
11 return{
12 create:createMember,
13 get:getMemberDetails
14 }
15 }();
16 // Now write myApplication.get() and myApplication.create() .


I call this the "revealing module pattern."

Configurable
Once I publish the JavaScript code I write to the world, someone wants to change it. Usually people want it to do something that it can't do on its own—but usually the program I write is not flexible enough to provide users. Defined features. The solution is to add a configuration item object to your script. I have written an article that provides an in-depth look at JavaScript configuration item objects. Here are the main points:

Add an object called configuration to your script.
Inside this object, store everything that people often change when using this script:
CSS ID and class name;
The name of the button, the label word, etc.;
Values such as "the number of pictures displayed per page", the value of "the size of the displayed image";
Location, location, and language settings.
This object is returned to the user as a public property so that the user can modify it to override it.
Usually this is the last step in your programming process. I concentrated this in an example: "Five things to do to a script before handing it over to the next developer."

In fact, you also want your code to be useful to people and make some changes based on their individual needs. If you implement this feature, you will receive less emails from people who complain about your scripts that are confusing to you. These letters will tell you that someone has modified your script and it works.

Interact with the background
One of the most important things I've learned during so many years of programming experience is that JavaScript is a great language for developing interface interactions, but if you're dealing with numbers or accessing data sources, it's a bit overwhelming.

Initially, I learned JavaScript, which was used to replace Perl, because I hate having to copy the code into the cgi-bin folder to make Perl run. Later, I understood that I should use a back-office language to handle the main data, and nothing can be done by JavaScript. More importantly, we have to consider security and language features.

If I visit a web service, I can get the data in JSON-P format. I do it in the client browser and do all kinds of data conversion, but when I have the server, I have more Method to convert data, I can generate JSON or HTML format data back to the client on the server side, as well as cache data and other operations. If you understand and prepare for this, you will benefit in the long run and save a lot of headaches. Writing a program for a variety of browsers is a waste of time, use the toolkit!

When I first started web development, I struggled with the problem of using document.all or document.layers for a long time when I visited the page. I chose document.layers because I like the idea that any layer is my own document (and I wrote too much document.write to generate the elements). The layer mode eventually failed, so I started using document.all. I was happy when Netscape 6 announced that it only supported the W3C DOM model, but users didn't care about it. Users just see that this browser can't display what most browsers can display properly - this is our coding problem. We have written short-sighted code that can only be run in the current environment, and unfortunately, our operating environment is constantly changing.

I have 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 with this type of problem. They handle various browser problems by abstracting various interface implementations, such as version incompatibility, design flaws, etc., which save us from pain. Unless you want to test a beta version of the browser, don't add code that fixes the browser's flaws in your own program, because you are likely to forget to delete the problem when the browser has modified the problem. Code.

On the other hand, relying entirely on the toolkit is also a short-sighted behavior. Toolkits can help you develop quickly, but if you don't understand JavaScript in depth, you'll do something wrong.

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.