A common closure situation
1. There is a problem in the Problem description. I want to divide a request into multiple requests. For example, in the following example, we split a time period into 10 small time periods and request data respectively. Naturally, the following code is written:
For (var I = 0; I <10; I ++) {var dateRange ={}; dateRange. start = start + I * deta; dateRange. end = start + (I + 1) * deta-1; Ext. ajax. request ({url: ajax_url, params: {start: dateRange. start, end: dateRange. end ,}, success: function (response, options ){... // note that the closure is used here, And I has become the maximum value of conosystemic. log (I );}});}
As shown in the above Code, when the request result is returned, the print value of I is 10, and all the places where I is used (for example, it is wrong to calculate the time range ).
2 solution 2.1 extracting parameters is the most direct method. This method is also mentioned in references, but he mentioned other methods to achieve this.
function requestData(i) { var dateRange = {}; dateRange.start = start + i*deta; dateRange.end = start + (i+1)*deta - 1; Ext.Ajax.request({ url: ajax_url, params: { start: dateRange.start, end: dateRange.end, }, success: function (response, options) { ... conosle.log(i); } });}for (var i = 0; i < 10; i++) { requestData(i);}
2.2 set ajax to set the ajax request method for the synchronous mode (because Ext uses the asynchronous mode by default), which blocks the loop and won't rewrite I.
Ext. ajax. request ({url: ajax_url, // set to async: false, params: {start: dateRange. start, end: dateRange. end ,}, success: function (response, options ){...
3 References 1. javascript Closure (Closure)
The basic concepts of closures are mentioned (internal function blocks reference external block variables). The closure problem description and solution are as follows: Create a function and pass parameters. Similar to that in the field.
2. ExtJs4 notes (3) Ext. Ajax support for ajax
Description of ajax request functions in ExtJS