javascript cross-browser event system_javascript skills
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;i
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;i
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;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.
[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool