Home  >  Article  >  Web Front-end  >  More elegant event triggering compatibility_javascript skills

More elegant event triggering compatibility_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:00:30976browse

Various problems

Making the underlying interface compatible is nothing more than using if to determine which interface the client supports. The most famous example is the event:

Copy code The code is as follows:

var addEvent = function( e, what, how) {
if (e.addEventListener) e.addEventListener(what, how, false)
else if (e.attachEvent) e.attachEvent('on' what, how)
}

Two situations that may be encountered when binding events to elements are considered here - the standard W3C DOM interface and the interface provided by DHTML. Of course, this example is still crude, but it is enough to illustrate the problem.

The original method is to call the on-site judgment in the compatibility layer and enter the corresponding if branch. Obviously, this "on-the-spot judgment" method is not efficient. Later, people adopted this method:
Copy code The code is as follows:

if (MSIE) {
addEvent = function(e, what, how) {
e.attachEvent('on' what, how);
}
} else {
addEvent = function(e, what , how) {
e.addEventListener(what, how);
}
}

Bind different codes to addEvent after one judgment, thus eliminating the need to run time branch judgment.

Unfortunately, this problem is not trivial. First of all, it is a very outdated idea to bind "use attachEvent" and "client is MSIE" together. What if Microsoft's conscience finds out one day? This is happening now - IE9 clearly supports the DOM interface, and even DOM3 supports it. As a result, this "conscience discovery" move will break many front-end libraries and they will have to be forced to modify their code (just like when IE8 came). Moreover, this approach does not take into account "unknown clients" - as far as I know, after Google released Chrome, it also caused many class libraries to rewrite their code.
Feature Detection

How to do it? Feature detection can minimize the trouble caused by "new clients" - detect the features of the client through a set of codes defined when the class library is initialized, and use this set of detection values ​​to bind the class library code :
Copy code The code is as follows:

var supportsAddEventListener = !!(checkerElement.addEventListener);
if (supportsAddEventListener) {
addEvent = function(e, what, how) {
e.addEventListener(what, how);
}
} else if (supportsAttachEvent) {
addEvent = function(e, what, how) {
e.attachEvent('on' what, how);
}
}

Feature detection is actually Decouple "use a certain client" and "support a certain feature" - let the if branch directly judge "whether the feature is present" (whether the interface is consistent), thereby eliminating the "good intentions" caused by the "conscience discovery" of the client manufacturer Do bad things." In fact, this is also in line with the historical trend - when standard interfaces gradually become popular and clients gradually become "consistent in representation", why not create a consistent compatibility layer interface?
Falling

Let’s take a look at the code again. Usually, a piece of code that uses feature detection for compatibility often looks like this:
Copy code The code is as follows:

if (new_interface_detected) {
comp = function() {uses_new_interface};
} else if (old_interface_detected) {
comp = function() {uses_old_interface};
} else {
throw new Error('Unadaptable!')
}

In other words, the process is:

If the client supports the new interface, bind the compatibility layer to the new interface
Otherwise, if the client supports the old interface/inconsistent interface, bind the compatibility layer to the new interface Bind to the old interface
Otherwise, if possible, give error feedback

That is, the compatibility layer program "dropped" from high altitude. If the client supports "advanced" features (new interface , standard interface), just "catch" it - the compatibility layer will have a home; otherwise, continue to fall - oh, if the old interface is caught, use the old interface; if no one has caught it, then - Snap - he fell to the ground and shouted with his last breath: "The client you are using is too niche, I can't do anything to you!"

What does this look like?

In fact, if you understand the mechanism of JavaScript object system, you can make an analogy: isn’t this a prototype! The prototype system takes advantage of this drop - look for a certain member, and if it is defined in this object, return it; otherwise, search upward along the prototype chain (yes, this time it is upward), and so on, until When the prototype chain really reaches the end, undefined is returned.

Just do it! Here we also use addEvent as an example. First, we define an empty driver, which contains nothing:

var nullDriver = {}

Then, we create an object and point the prototype chain to it. In the ECMA V5 era, we can use Object.create. Unfortunately, there are still many old clients (otherwise they are compatible), so we craft our own function:
Copy code The code is as follows:

var derive = Object.create ? Object.create: function() {
var T = function() {} ;
return function(obj) {
T.prototype = obj;
return new T
}
}()

You may think of this usage It's weird, but it works without any problems and is not slow - about half as fast as Object.create. We will use this derive to start:
Copy code The code is as follows:

var dhtmlDriver = derive( nullDriver);
var dhtmlDriverBugfix = derive(dhtmlDriver);

The bugfix here is a special Driver defined for some "bugs" and special situations. You can ignore it here. Okay, what is addEvent in DHTML?
Copy code The code is as follows:

if (supportsAttachEvent) {
dhtmlDriver.addEvent = function(e, what, how) {
e.attachEvent('on' what, how)
}
}

Then what? The one at the front of the prototype chain should be the W3C standard driver, write it down!
Copy code The code is as follows:

var w3cDriver = derive(dhtmlDriverBugfix);
var w3cDriverBugfix = derive(w3cDriver);

if (supportsAddEventListener) {
w3cDriver.addEvent = function(e, what, how) {
e.addEventListener(what, how)
}
}

Finally, we will put something on it to make the final call interface. (Because w3cDriverBugfix is ​​too ugly...)

var driver = derive(w3cDriverBugfix);

Then it is called. Look, this makes those scary-looking branch judgments simple and effective, without losing the true nature of fallback: calling addEvent on a client that supports addEventListener is equivalent to calling w3cDriver.addEvent, and it will fall to the bottom on a client that does not support addEventListener. Next, for example, call dhtmlDriver.addEvent. In addition, it is easy to perform bugfixes - you can hook in a dedicated "bugfix" layer, while the original layer is not affected at all.
Wait a minute, will inheriting so many layers

be very slow? Admittedly, such a deep prototype chain will definitely be slow, but I have a way. Remember what happens when you write to an object's properties?
Copy code The code is as follows:

var ego = function(x) {return x}
for (var each in driver) {
if (! (each in nullDriver)) {
driver[each] = ego(driver[each])
}
}

Yes, the method that was originally high on the prototype chain will suddenly fall to the bottom! This time there is no need to search up the prototype chain, just get the properties directly from the bottom. The reason for using the ego function here is to prevent some browsers from "optimizing" the code here.
Summary

Although we talk about compatibility here, its essence lies in the language features - using prototypal inheritance, we can complete this troublesome operation very elegantly. Yes, the beauty of a frame should not only be on the outside, but also on the inside - even the most annoying ones - should be equally elegant.

The technology here can be found in dess.
From:typeof.net
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn