But in fact, the father of JavaScript cannot dominate all this. The Netscape he supported is not strong enough to allow competitors to use its products obediently. Microsoft has created a JScript, the dead Macromedia has created an ActionScript, and there are many more. I heard that this branch is quite complicated. But using the built-in DOM event model of the browser, the first consequence is that if you want to use it, you must use a DOM object, window, document or element node. The second consequence is that each browser has different support for DOM. , cannot ensure the consistency of the event model, and the third is because it is based on DOM objects, which can easily cause circular references. After Microsoft won the first browser war, it basically did not update its DOM model. It was divided into two camps with the "standard browsers" that were constantly updated to move closer to w3c, ecma and other standards. However, standard browsers are not monolithic. For example, FF does not support mousewheel but DOMMouseScroll, and opera's contextmenu is uncontrollable. We need to implement it ourselves. At present, both hosts implement the DOM2 event model. Microsoft's is attachEvent, and the standard one is addeventListener, which allows the same element to bind multiple event callback functions of the same type. Many addEvent functions on the Internet are made using them, but they are not reliable. First of all, IE's callback function does not force the event object to be bound, and the standard browser is that the first parameter of Qiangwuqu is the event object, although we can use The call function implements forced binding, but IE's event object is also different from the standard one. There is a lot of work to be done here. Another issue is the execution order of callback functions. IE is irregular, and the standard is to execute them in the order of binding. Therefore, these two functions are also negated. I plan to use the original onXXXX to implement it. When binding multiple functions, put them into one function and complete it with a for loop.
Let’s review the above process. This event system is actually a modified version of Dean’s addEvent.
Set an object as a namespace.
Make some extensions to Array.
attachEvent function is used to bind events. The specific method is to set an events attribute in the object that needs to bind the event, and then place the callback function according to the event type. Since sometimes we may bind 2 or more onclick events on the same element, they must be an array. . Finally, add an onXXXX attribute using the original method of DOM0.
The detachEvent function is used to unload events, which is to remove the array elements of the corresponding type from events.
handleEvent executes the callback function. We have bound a global function in the form of onXXXX. Its function is to obtain and modify the event object, then obtain all callback functions corresponding to this event type, and then execute them in turn using the event object as their first parameter. The last step is to deal with bubbling.
fixEvent fix event object. Basically, there are two ways to make IE have a standard browser.
For general applications, it is sufficient. But if you pursue perfection. We still have a lot to use. First of all, it is very inappropriate to put the huge object of events on the element, which is not conducive to centralized management. Second, fixEvent is not thorough. Properties under standard browsers such as target and pageX/Y are still unavailable in IE.
The first is the handleEvent function. Now the event object of both standard browsers and IE needs to be modified. Its currentTarget value is also modified for IE every time it is called.
dom.handleEvent = function (event) {
event = event || window.event
event = dom.fixEvent(event);
event.currentTarget = this;//Fix currentTarget
var returnValue = true;
var handlers = this.events [event.type];
for(var i=0,n=handlers.length;iif (handlers[i](event) === false) {
returnValue = false;
}
}
return returnValue;
};
When we introduce the new version of the fixEvent function, we first introduce it to me, which I stole from jQuery Pseudo event object.
dom.oneObject = function(arr,val){
var result = {},value = val !== undefined ? val :1;
for(var i=0,n=arr.length;iresult[arr[i]] = value;
return result;
};
dom.mixin = function(result, source) {
if (arguments.length === 1) {
source = result;
result = dom;
}
if (result && source ){
for(var key in source)
source.hasOwnProperty(key) && (result[key] = source[key]);
}
if(arguments.length > 2 ){
var others = [].slice.call(arguments,2);
for(var i=0,n=others.length;iresult = arguments.callee(result,others[i]);
}
}
return result;
}
var MouseEventOne = dom.oneObject(["click","dblclick","mousedown",
"mousemove","mouseout", "mouseover","mouseup"],"[object MouseEvent]");
var HTMLEventOne = dom.oneObject(["abort","blur","change","error","focus",
"load","reset","resize","scroll","select","submit","unload"],"[object Event]");
var KeyboardEventOne = dom.oneObject(["keyup","keydown","keypress",],
"[object KeyboardEvent]");
var EventMap = dom.mixin({},MouseEventOne,HTMLEventOne,KeyboardEventOne)
var fn = "prototype";
dom.Event = function( src ) {
if ( !this.preventDefault ) {
return new dom.Event[fn].init( src );
}
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
dom.Event[fn] = {
init:function(src){
//如果传入的是事件对象
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
//如果传入的是事件类型
} else {
this.type = src;
}
this.timeStamp = new Date().valueOf();
this[ "expando" ] = true;
},
//http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/events.html#Conformance
toString:function(){
return EventMap[this.type] || "[object Event]"
},
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// 如果存在preventDefault 那么就调用它
if ( e.preventDefault ) {
e.preventDefault();
}
// 如果存在returnValue 那么就将它设为false
e.returnValue = false;
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// 如果存在preventDefault 那么就调用它
if ( e.stopPropagation ) {
e.stopPropagation();
}
// 如果存在returnValue 那么就将它设为true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
dom.Event[fn].init[fn] = dom.Event[fn];
这个构造函数只实现了W3C事件模型的少许方法,那些属性去了哪?不急,我们在fixEvent方法中通过拷贝方式实现它们。为了区别原生事件对象与伪事件对象,我们在它上面添加了一个expando属性。
var buttonMap = {
1:1,
4:2,
2:3
}
dom.fixEvent = function(event){
if ( event[ "expando" ] ) {
return event;
}
var originalEvent = event
event = dom.Event(originalEvent);
for(var prop in originalEvent){
if(typeof originalEvent[prop] !== "function"){
event[prop] = originalEvent[prop]
}
}
//If the target attribute does not exist, set it for it Add a
if ( !event.target ) {
event.target = event.srcElement || document;
}
//If the event source object is a text node, place its parent element
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
//If the relatedTarget attribute does not exist, add one for it
if ( !event.relatedTarget && event.fromElement ) {
event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
}
//If it does not exist pageX/Y is combined with clientX/Y to make a pair
if ( event.pageX == null && event.clientX != null ) {
var doc = document.documentElement, body = document.body;
event.pageX = event.clientX (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
}
// is the keyboard Event adds which event
if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) {
event.which = event.charCode || event.keyCode;
}
// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
if ( !event.metaKey && event.ctrlKey ) {
event.metaKey = event.ctrlKey;
}
// Determine which key was pressed in the mouse event, 1 === left; 2 === middle; 3 === right
if ( ! event.which && event.button !== undefined ) {
event.which = buttonMap[event.button]
}
return event;
}
milli Do not hesitate to copy jQuery's methods, because among all class libraries, jQuery's methods are the best to extract.
Now we have basically solved one of the two questions raised in the middle of the article. To solve the first one we need to introduce a caching system. This is left to the next section.
]