JavaScript realization of the lottery Activity example code Analysis and Optimization (ii) _JAVASCRIPT skills

Source: Internet
Author: User
Tags closure extend sin

In the last article, we introduced the JavaScript to achieve the lottery Activity example code Analysis and optimization (i), since is to write Plug-ins. Then what is called "plug-in" must have some characteristics that can meet the needs of our development or improve our development efficiency. So what are the basic features of what is called a plugin? Let's summarize:

1.JavaScript Plug-ins some basic features:

Configuration must be simple
The variables defined in the plug-in do not pollute the global variable;
The same piece of code can be reused in different places;
Users can customize their own functional parameters;
Having the function of destroying variables and parameters;
If you follow the above features to write plug-ins, we can summarize a basic code structure, we look at one by one:

1. Plug-in configuration to be as simple as possible

Configuring container nodes in HTML

The node-type= "Reward-area" Here is the container node that identifies our plug-in <div class= "Re-area" node-type= "Reward-area"
>

Initialize the plug-in after the DOM load completes

$ (function () {
///The test here is the class window that represents the container
. Lightrotate.init ($ (' [Node-type=reward-area] '));

2. Variables defined in Plug-ins do not pollute global variables

JavaScript has a block-level scope identifier that is a function. So how do we declare our variables so that they don't pollute the global variables?
Here we need to use a JavaScript function of the self implementation of the knowledge point. The code is as follows:

(function () {
//do Something
}) ();

3. Reusing functional codes in different places

This is to use our object-oriented knowledge point, our functional code abstract as an object, when we need to use, instantiate the object can be. Then we'll go on to the second code and write,


(function ($) {
///Create feature object
var lightrotate = function (select) {
//do something
};
Lightrotate.init = function (select) {
var _this = this;
Different object
Select.each (function () {
new _this ($ (this))
is instantiated according to different containers; Window. Lightrotate = lightrotate;
}) (JQuery);

4. User can customize function parameters

First we should have the default parameter settings, such as the following


(function ($) {
///Create feature object
var lightrotate = functions (select) {
//custom parameters
this.setting = {
Liautoplay:false,//around the lights are automatically rotated
rolispeed:100,//lights rotate the speed of Ms
roprspeed:200,//Prizes rotate speed Ms
Lidirection:true,/ /rotation direction true positive direction false reverse direction
Randomprize:false//Space whether randomly select
};
Lightrotate.init = function (select) {
var _this = this;
Different object
Select.each (function () {
new _this ($ (this))
is instantiated according to different containers; Window. Lightrotate = lightrotate;
}) (JQuery);

In fact, the user can modify our JavaScript file to complete the customization. But in order to be able to make our difference enough to use, for example, our users do not know a bit of JS? What should I do?
This allows us to configure these parameters with custom attributes in HTML, as follows:

<div class= "Re-area" node-type= "Reward-area" data-setting= ' {
"Liautoplay": false,
"Rolispeed": 100,
"Roprspeed": "
lidirection": True,
"Randomprize": false} ' >

This allows the user to configure the parameters of the current container to run only in the HTML node. Such benefits can also enable different containers on the same page to be individually configured with parameters that reduce coupling.

So how do we get these parameters in JS? In the above code, there is already a function object function. So what do we do if we want to extend the object method to get the user's custom parameters? We generally use prototype to extend the methods of our existing objects, the code is as follows:


(function ($) {
///Create feature object
var lightrotate = functions (select) {
//custom parameters
this.setting = {
Liautoplay:false,//around the lights are automatically rotated
rolispeed:100,//lights rotate the speed of Ms
roprspeed:200,//Prizes rotate speed Ms
Lidirection:true,/ /rotation direction true positive direction false reverse direction
Randomprize:false//Space whether randomly select
};
This invokes the method of obtaining the user-defined parameters of the object and merges the default parameters
$.extend (_this.setting, _this.getsettinguser ());
Lightrotate.prototype = {
//extension of methods to get user-defined parameters
Getsettinguser:function () {
var usersetting = this. Lightarea.attr (' data-setting ');
if (usersetting && usersetting!== ') {return
$.parsejson (usersetting);
} else {return
{};
   }}}
;
lightrotate.init = function (select) {
var _this = this;
Different object
Select.each (function () {
new _this ($ (this))
is instantiated according to different containers; Window. Lightrotate = lightrotate;
}) (JQuery);

5. Function of destroying variables and parameters;

The last one is that our plug-ins should have the ability to destroy their own variables and parameters. How do we write it? Or you can continue to extend the callable method of the feature object based on the above code, as follows:

Lightrotate.prototype = {
//extension of methods to get user-defined parameters
Getsettinguser:function () {
var usersetting = this. Lightarea.attr (' data-setting ');
if (usersetting && usersetting!== ') {return
$.parsejson (usersetting);}
else {return
{};
}
},
//Destroy object parameter
destory:function () {
$ (_this). Lightarea). Off ();
This.closeanimation ();
This.rewardtimer = null;
}
} ;

From the above we can probably understand a mature plug-in should have the basic functionality.

2. Plug-in development and optimization examples

Just before the Spring Festival holiday, this project is an urgent project, in order to hurry up without thinking about their own code structure, so the game's own follow-up optimization provides an opportunity.

The contents of the timer described in the previous section tell you that JavaScript is single-threaded. So

If a piece of code runs inefficiently, it can affect the execution of subsequent code. So for JavaScript, code optimization is a must.
Let's take a look at what our "Happy Lights" plug-in should have:

Be able to control whether the light is automatically played;
The direction of rotation of the lamp can be controlled;
The rotation speed of the lamp can be controlled;
The rotation speed of the prize can be controlled;
The development process of these function points is not described in detail here, only the optimization process is introduced. If you are interested can see my article last attached source code address, for download reading.

1. "Order" to obtain the rotation Lamp code optimization

Because the lights around me are using absolute positioning to do, so I need "order" to get their list and then operate.

Gets the DOM node first.

To get the outer lights, you can see the selector I use here is one more select to get some elements under the current container, to avoid conflicts when multiple containers exist
This.toplight = $ (' [node-type=re-top] ', select) . Find (' span ');
This.rightlight = $ (' [node-type=re-right] ', select). FIND (' span ');
This.bottomlight = $ (' [Node-type=re-bottom] ', select). FIND (' span ');
This.leftlight = $ (' [Node-type=re-left] ', select). FIND (' span ');

Then you should get a list of the DOM elements of the lights node in order.

My first edition was to do this:

Zepto (Toplight). each (function () {
lightlist.push (this);
});
Zepto (RightLight). each (function () {
lightlist.push (this);
});
for (var j = bottomlight.length-1 J >= 0; j--) {
lightlist.push (bottomlight[j]);
for (var m = leftlight.length-1 m >= 0; m--) {
lightlist.push (leftlight[m]);

Because the "down" and "left" direction of the light is needed in reverse, so I used two reverse for loop, in fact, when the loop appears, we should consider whether our code has a space to optimize.

The optimized code is like this, where I've reduced the use of 4 cycles

function () {
var lightlist = [];
var bottomrever;
var leftrever;
Bottomrever = Array.from (this.bottomlight). reverse ();
Leftrever = Array.from (this.leftlight). reverse ();
Lightlist = Array.from (this.toplight). Concat (Array.from (this.rightlight));
Lightlist = Lightlist.concat (bottomrever);
Lightlist = Lightlist.concat (leftrever);
}

Reverse list I used the reverse method of the native array object.

2. Using "closures" to optimize sequential loop seeding

In order to be able to make our "lights" in order to run up, the first version of the idea is:

To every "lamp" (note, here is every one, sin ...) Sin... To define a settimeout (), the execution time is to add a number of sequences to the JS execution queue.
The code is the following:

var zepto_light = Zepto (lightlist);
var changetime = m;
var lightlength = zepto_light.length;
var totletime = changetime * LIGHTLENGTH;
function Lightopen () {for
(var i = 0; i < lightlength; i++) {
(function temp (i) {
Lighttimer = settimeout ( function () {
if (StopAnimation = False) {
Zepto (zepto_light). Removeclass (' Light_open ');
Zepto (Zepto_light[i]). addclass ("Light_open");
else {return
;
}
}, Changetime * i);
} (i);
}

The disadvantage of this writing is obvious: if I have 100 "lights" then will be in the current JS execution queue to add 100 settimeout (), again, I use the For loop here again, in the time complexity of the increase. The execution of the code has fallen again.

Later thinking, JavaScript in the "closure" with my current use of the scene, I want to use the closure optimization, the following code:

Lightrun:function () {
var _this = this;
function Tempfunc () {
var lightlist = _this.getlightlist ();
var lightlength = lightlist.length;
var i = 0;
return function () {
$ (lightlist, _this. Lightarea). Removeclass (' Light_open ');
$ (lightlist[i], _this. Lightarea). addclass ("Light_open");
i++;
Enables the next loop to continue after a round loop
if (i = = = Lightlength) {
i = 0;}}
;
}
var lightrunfunc = Tempfunc ();
Lightrunfunc ();
_this.lightinterval = SetInterval (Lightrunfunc, _this.setting.rolispeed);
}

The above code can obviously find two advantages: first, reduce the use of the For loop, reduce the time complexity of the code, and secondly, every time I only in the current code execution queue to create a setinterval (). Reduces the complexity of execution queues.

About JavaScript realization of the lottery activities example code Analysis and Optimization (ii) of the relevant knowledge to be introduced here, I hope this article described to help everyone.

Related Article

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.