Issues to handle event attention __function

Source: Internet
Author: User

Recently in the fine reading MooTools core source code, reading to the packaging event, only to find that the JS event processing mechanism has not been in-depth research. So, again opened the dusty old Java Rhino Book, carefully read a.

We are writing JS program, to a large extent, are writing client-side interaction program, so most can be related to events. Unfortunately, the details of these event handlers are very complex. And because of browsers, there are currently four different event-handling mechanisms:

Original Event Model: This is the simplest kind of event-handling model, and despite its limited functionality, all browsers support it. You can think of it as Level 0 dom.

Standard Event Model: This is a more powerful and complete event model. The Level 2 DOM standard has standardized it. Netscape 6 and Mozilla support it

Internet Explorer Event Model : Many features that have a standard event model. Although Microsoft participates in the creation of the Level 2 DOM event model. But IE7 version does not achieve the standard of Level 2 model, adhere to the use of their own proprietary event model, IE8 the above is not clear. This means that when running under IE, a JS program that wants to use advanced event handling features must write specific code.

Netscape Event Model: This model is now replaced by the Standard Model. But Netscape6 continues to implement it for backwards compatibility.

Next we discuss the characteristics of each of these event models and how to implement a universally robust event handler in your application

In fact, when we deal with the JS event problem, we will naturally think that the event occurred on the target element, then its event processing code will only be written in the specific processing functions you write, such as: The Code: HTML code <div id= " Parent "style=" height:100px; width:200px; Background-color:yellow "onclick=" Parent (event) "> <div id=" Child "style=" height:50px; width:100px; Background-color:gray "onclick=" Child (event)> </div> </div>

		<div id= "Parent" style= "height:100px; width:200px; Background-color:yellow "onclick=" Parent (event) ">
			<div id=" Child "style=" height:50px; Background-color:gray "onclick=" Child (Event) >
			</div>
		</div>

JS Code var parent = function(e) {alert (' parent ');    };    var child = function(e) {alert (' child '); };

			var parent = function (e) {
				alert (' parent ');
			var child = function (e) {
				alert (' child ');
			

In general, we think that when you click Parent, you print ' parent ', and when you click on the child, it prints ' child ', but otherwise, when you click on the child, it prints out ' parent ' and ' child '. Why the result is not the same as expected, it is because our event processing mechanism for JS is also based on the original event model. The browser is handled in accordance with the standard event model. Then maybe someone has a question, not that IE does not support the standard event model? Why the "Child" is also printed under IE and parent. We just said IE used its own professional event model processing mechanism. But it has the characteristics of most of the standard event models. So we'll see how the standard event model is defined.

In the original event model, the browser assigns the event to the document element where the event occurred. If the object has an appropriate event handler, run the program. For the first time, you do not have to perform other operations. However, in the standard event model, the situation is much more complex. When an event occurs on the target element, the target's event handler is triggered. In addition, each ancestor node of the target also has the opportunity to handle that event. Event propagation is done in three phases. One: During the capture (capturing) phase, the event propagates down the document object to the target node. During this time, any ancestor node of the target object can capture events and process it. Two: The target node itself, this is similar to the original time model, and the last stage is the bubbling phase: at this stage, the event propagates up from the target element back to the document hierarchy of the Documents object.

Now it's not hard to see why the parent's Click event handler is also executed when we click on the child. This is the subject of our discussion today, the neglected details. Although many people know the JavaScript standard event model, Most people ignore these problems when they write event handlers. So, sometimes, in a section of the page JS code inserted a few pieces of event code, but produced inexplicable errors or with the desired results have a big discrepancy. If you haven't had a problem like this, you should be thankful for it, That's because you've never met a parent element and a child element that handles the same event. But that doesn't mean you'll never meet. So for your code to be robust and maintainable. You should refactor your code. The following code is one of my implementation JS codevarEvent =function(event) { This. event = Event | | window.event; This. target = (function() {vartarget = This. event.target | | This. event.srcelement; while(Target && target.nodetype = 3)                {target = Target.parentnode; } returnTarget })(); This. Stop =function(){ return This. Stoppropagation (). Preventdefault (); } This. stoppropagation =function(){if( This. event.stoppropagation) This. Event.stoppropagation ();Else This. event.cancelbubble =true; return This; } This. Preventdefault =function(){if( This. Event.preventdefault) This. Event.preventdefault ();Else This. Event.returnvalue =false; return This; }    }

var Event = function (event) {
		this.event = event | | window.event;
		This.target = (function () {
			var target = This.event.target | | this.event.srcElement;
			while (target && target.nodetype = 3) {
				target = Target.parentnode;
			}	
			return target;
		}) ();
		
		This.stop = function () {return
			this.stoppropagation (). Preventdefault ();
		}
		
		This.stoppropagation = function () {
			if (this.event.stopPropagation) this.event.stopPropagation ();
			else this.event.cancelBubble = true;
			return this;
		}
	
		This.preventdefault = function () {
			if (this.event.preventDefault) This.event.preventDefault ();
			else This.event.returnValue = false;
			return this;
		}

Event handling code after refactoring: JS code var parent = function(e) { var event = New event (e);    Alert (' Parent ');    };        var child = function(e) { var event = New event (e);        Alert (' child ');    Event.stoppropagation (); };

			var parent = function (e) {
				var event = new event (e);
				Alert (' parent ');
			var child = function (e) {
				var event = new event (e);
				Alert (' child ');
				Event.stoppropagation ();
			};

After this process, you will be guaranteed to operate as usual in any environment

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.