当前位置:网站首页>[source code interpretation] JS native message prompt plug in

[source code interpretation] JS native message prompt plug in

2021-01-23 18:45:33 itread01

The effect is as follows :

Shut down message Before and after message The connection is very smooth , I'm more interested in this part . Take this question with you first DOM Structure , By the way, sort out the author's ideas .

 

 

From DOM We can see all of them in the library message It's all in one container , And this container has done absolute positioning to achieve the horizontal center of the visual window , Newly added message Just in the container append The corresponding element will be displayed on the page .

Now let's take a look at each message The secret of elements ~

 

 

 

We can see that it's set up here height and padding Animations of properties , The animation rate above is set when it is turned off height and padding For 0, Because bfc The rules before and after the animation period message It's going to take up space , So it looks silky . When the animation is finished, the elements are remove fall .

Here's a less common one css Properties :will-change, quoted MDN The expression on the table , This property will be optimized in advance according to the value specified by the developer .will-change

Other internal elements are common, rendering according to the type and message of the box , No more scrutiny . Next, focus on js On .

The introduction is simple , Only one js Archives

The code example is as follows :

 1 //  Configure global default arguments  2 cocoMessage.config({ 3    duration: 10000, 4 }); 5 //  General information , Automatic closing time can be passed in 、 Tips 、 Turn off callback  6 cocoMessage.info(3000, " Please log in first !", function () { 7     console.log("close"); 8 }); 9 //  Success message , Can pass in element Elements 10 var div1 = document.createElement("div");11 div1.innerText = " Modification successful !";12 cocoMessage.success(div1);13 //  Warning message , Time setting 0 It won't shut down automatically 14 cocoMessage.warning(" You need to turn it off manually ", 0);15 //  Failure message 16 cocoMessage.error(" Modification failed !", 3000);17 // loading Message 18 var closeMsg = cocoMessage.loading(true);19 setTimeout(function () {20     closeMsg();21 }, 4000);22 //  Turn off all messages 23 cocoMessage.destroyAll();

  Here we can see that the types of support are info、success、warning、error、loading Five kinds , The basic scenes cover . It's more flexible , One, two, three , And the type is not fixed . With these questions, the real code walkthrough begins , Unravel its mystery :

First, look at the code structure :

 

  It defines a compatible _typeof Method ( Forgive me for not understanding this compatible logic , If you understand, you can leave a message in the comment area ); Then there's a common immediate function , Before the function ! It's the same as wrapping it in brackets , It's common to see +-.

Pass in two arguments , The first is void 0( That is to say undefined, It's a personal feeling this No problem , Interested can learn about ), Another argument is the body function , I'll give you more details later , Let's take a look at what the immediate executor does :

First check if there is module.exports Check again define.amd, Finally, we use global variables . Obviously this is compatible CommonJs Regulate 、AMD/CMD Standard and direct reference writing . Among them global = global || self It's not... It's not window Because it can be compatible with the server side (global Global variable ) And browser side (window Global variable ). This will be in the browser window Exposure to variables cocoMessage Variables . In addition, using the immediate function can avoid polluting global variables . Before going inside the method , It is suggested that you collect this part of the code

1 !function (global, factory) {2   (typeof exports === "undefined" ? "undefined" : _typeof(exports)) === "object" && typeof module !== "undefined" ? 3   module.exports = factory() : 4   typeof define === "function" && define.amd ? 5   define(factory) : 6   (global = global || self, global.cocoMessage = factory());7 }(void 0, function () {8   // code here9 });

 

Just entering the method will establish msgWrapper The variable stores the parent element of the message , Define the default configuration initArgs, expose cocoMessage Variable and add after loading page elements style Label . The white note in the figure above is a common method , The following will focus on the red note method .

First, focus on building msgWrapper Elemental c Method :

The first argument transfers the object ,key It can be className To add class Properties , Another way is to _ The beginning can bind the corresponding event to the element .

The second argument can transfer text 、 Elements 、 An array of multiple elements ( Or pseudo array ).

//  establish class For coco-msg-stage Of div Elements var msgWrapper = c({   className: "coco-msg-stage"}, " Default message ");//  establish class For coco-msg-wait And bind to the elements click event c({    className: "coco-msg-wait " ,    _click: function _click () {      if (closable) {        closeMsg(el, onClose);      }    }}//  Multiple calls establish complex elements c({   className: "coco-msg-stage"}, c({   className: "coco-msg-loading",   _click: function(){       console.log("loading")   }}));
Then look at initArgs and cocoMessage These two variables

 

share info、success、warning、error、loading、destoryAll、config These seven methods , This is what the plug-in wants to expose to users . The message in the default argument is an empty string , The closing time is 2s, The close button is not displayed , Of course, all of this can be done through config Method to modify the global default configuration , You can also see that the configuration can be modified at any time , Immediate effect . remove destoryAll Method let's first focus on the message 5 Medium size , The method of establishment is similar : All through initConfig Method established . among arguments It's a pseudo array , That is, we call info And so on , The value can be obtained by the same way as the corner mark of the pass array .loading The method is special , hold initConfig Method is returned , Through demo We know that the return value is a method , It will close after execution loading, Now let's focus on loading What's the special handling of type information , Start getting into initConfig Method .

 

 

  Here is only the unification of arguments , There is a question above , Why can arguments be passed freely , And the inconsistency of order doesn't affect ? The answer is in this method , The arguments passed before have information : String (string Type ) Or elements (Element or object Type )、 Delay time : Numbers (number Type )、 Call back after closing : Method (function Type )、 Whether to display the close button (boolean Type ). We should find the mystery here , Each argument has a unique type and does not conflict , In this way, you can identify the value of the parameter according to the type of the parameter . The packaged objects are as follows :

{   msg: " Prompt message ",   type: "info",   showClose: false,   duration: 2000,   onClose: function(){       console.log("closed")     }}

Although the above method is cleverly designed , But less robust , If you want to expand the package, set whether the text is centered 、 Custom class name 、 When you customize functions such as icons, you have to refactor them . So changing the call method to this will make it easier to expand the suite :

cocoMessage.info({    msg: ' Please log in first ',    duracion: '2000',    showClose: true,    onClose: function(){        console.log('closed')    }});

At this point, the required argument encapsulation is complete , The next call is createMsgEl Method to create a message element .

  The method is divided into two parts , Complete the creation of elements based on the passed in arguments and add them to body It shows , And bind the click event of the close button and the condition that triggers the automatic close . The picture in the picture says hello to the question we have in doubt above , Because the method of closing message is returned here, it can close after execution loading.

There's still closeMsg Methods and destoryAll Method , Let's see first closeMsg:

 

  First of all, it will set padding and height For 0, And then realize the animation effect at the beginning , Then execute the custom method of closing callback . Finally, delete the message element , If there is no message, the parent element will also be deleted . It should be noted that the existence of message elements will also be judged here , This is not redundant code , Instead, it takes into account the problem that an error will be reported when the click button is closed and the execute all close are executed together , Because there are 300ms The delay of .

And finally destoryAll Method , Turn off all messages .

 

  Get all the message elements of the parent element and call back closeMsg Method to delete .

  Here, the native message indicates that the plug-in has been interpreted , This is a very lightweight and excellent plug-in .
 
Summary :
First, avoid global variable pollution by executing functions immediately , There are only seven ways to expose yourself . Through the variable detection to achieve CommonJs Regulate 、AMD/CMD Compatibility of specifications and direct references . Through ingenious argument design , There is no requirement for the order of arguments , By setting padding and height Value to achieve the animation effect .
highlight :
Set will-change Of css Attributes improve performance and user experience ;
Through compatible listening elements animationEnd Event to perform callback , Solved setTimeout Inaccuracy and efficiency issues ;
Through c Methods can easily create elements , A little bit react The smell of ;
to svg Animating inner elements ;
 
Plug in preview address :https://www.jq22.com/jquery-info236

版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/01/20210123184315022x.html

随机推荐