Long process blocks waiting icon render in ExtJS - extjs

The feature I'm implementing is not a really required, so I won't include an extra library of threads just for that. But if someone knows a workaround I will appreciate it.
So I have a grid of 256 rows and 3 columns; one those columns is a checkboxColumn (similar to the one used here). But that checkboxColumn plugin has being modified to show a checkbox in the header in order to allow a kind of Check-All and Check-None features.
Because there are so many rows, the check-all process is taking to long. So I decided to put a "Spinning wheel" (waiting gif-animation). And now the problem is that the animation doesn't work. So I put a defer call to allow the rendering of the animated icon, but it seems like that defer is not enough for the animation to run. Although this defer at least allows showing the first frame of the waiting gif, instead of showing the checked-state for about a minute until the unchecked-state is show when everything is done.
Here is the expensive method:
internalSetAllColumn: function(column, newValue) {
column.masterValue = newValue;
column.header = '<div class="x-grid3-check-col-td loading-indicator"> </div>'; // loading icon
this.grid.getView().updateHeaders();
(function() {
this.grid.getStore().each(function(rec) {
if (this.isCellEditable(rec)) {
rec.set(this.dataIndex, newValue);
}
}, this);
column.renderHeaderCheck();
this.grid.getView().updateHeaders();
}).defer(50, this);
}
And you can see a working example at the following code snippet:
/*global Ext */
Ext.grid.CheckColumn = function(config){
Ext.apply(this, config);
if(!this.id){
this.id = Ext.id();
}
this.headerText = this.headerText || this.header || ' ';
this.renderer = this.renderer.createDelegate(this);
};
Ext.grid.CheckColumn.prototype = {
init: function(grid) {
this.grid = grid;
var column = this.grid.getColumnModel().getColumnById(this.id);
column.masterValue = false;
if (this.headerCheck) {
column.renderHeaderCheck();
}
this.grid.on('headerclick', this.onHeaderClick, this);
this.grid.on('render', function() {
var view = this.grid.getView();
view.mainBody.on('mousedown', this.onMouseDown, this);
view.updateHeaders();
}, this);
}
, dataIndex: ''
, masterValue: false
, width: 90
, fixed: true
, headerCheck: false
, enableHeaderControl: true
, onMouseDown: function(e, t) {
if (!this.readonly) {
if (Ext.fly(t).hasClass('x-grid3-cc-' + this.id)) {
e.stopEvent();
var editEvent = {};
editEvent.row = this.grid.getView().findRowIndex(t);
editEvent.column = this.grid.getColumnModel().findColumnIndex(this.dataIndex);
editEvent.grid = this.grid;
editEvent.field = this.dataIndex;
editEvent.record = this.grid.store.getAt(editEvent.row);
editEvent.originalValue = editEvent.record.data[this.dataIndex];
editEvent.value = !editEvent.originalValue;
editEvent.record.set(editEvent.field, editEvent.value);
editEvent.grid.fireEvent('afteredit', editEvent);
}
}
},
getCheckedCls: function(v) {
return v === -1 ? 'x-grid3-check-col-gray' : (v ? 'x-grid3-check-col-on' : 'x-grid3-check-col');
},
renderHeaderCheck: function() {
this.header = '<div class="' + this.getCheckedCls(this.masterValue) + '">' + this.headerText + '</div>';
},
onHeaderClick: function(grid, columnIndex, event) {
var colModel = grid.getColumnModel();
var cIndex = colModel.getIndexById(this.id);
if (cIndex == columnIndex && this.enableHeaderControl !== false && this.headerCheck) {
var column = colModel.getColumnById(this.id);
var newValue = !column.masterValue;
this.internalSetAllColumn(column, newValue);
colModel.fireEvent("headerchange", colModel, columnIndex, column.header);
this.grid.getView().updateHeaders();
}
},
renderer: function(v, p, record, rowIndex, colIndex, store) {
p.css += ' x-grid3-check-col-td';
return '<div class="' + this.getCheckedCls(v) + ' x-grid3-cc-' + this.id + '"> </div>';
},
internalSetAllColumn: function(column, newValue) {
column.masterValue = newValue;
column.header = '<div class="x-grid3-check-col-td loading-indicator"> </div>'; // loading icon
this.grid.getView().updateHeaders();
(function() {
this.grid.getStore().each(function(rec) {
rec.set(this.dataIndex, newValue);
}, this);
column.renderHeaderCheck();
this.grid.getView().updateHeaders();
}).defer(50, this);
},
setAllColumn: function(columnIndex, newValue) {
var colModel = this.grid.getColumnModel();
var colId = colModel.getColumnId(columnIndex);
var column = colModel.getColumnById(colId);
this.internalSetAllColumn(column, newValue);
this.grid.getView().updateHeaders();
}
};
// -----------------------------------------
// End of plugin - Beginning of example code
// -----------------------------------------
var chkColCountry = new Ext.grid.CheckColumn({ dataIndex: 'State.After', width: 50, headerCheck: true });
var dsCountries = new Ext.data.ArrayStore({
fields: ['Id', 'Name']
, data: [["US","United States"],["CA","Canada"],["AF","Afghanistan"],["AL","Albania"],["DZ","Algeria"],["DS","American Samoa"],["AD","Andorra"],["AO","Angola"],["AI","Anguilla"],["AQ","Antarctica"],["AG","Antigua and/or Barbuda"],["AR","Argentina"],["AM","Armenia"],["AW","Aruba"],["AU","Australia"],["AT","Austria"],["AZ","Azerbaijan"],["BS","Bahamas"],["BH","Bahrain"],["BD","Bangladesh"],["BB","Barbados"],["BY","Belarus"],["BE","Belgium"],["BZ","Belize"],["BJ","Benin"],["BM","Bermuda"],["BT","Bhutan"],["BO","Bolivia"],["BA","Bosnia and Herzegovina"],["BW","Botswana"],["BV","Bouvet Island"],["BR","Brazil"],["IO","British lndian Ocean Territory"],["BN","Brunei Darussalam"],["BG","Bulgaria"],["BF","Burkina Faso"],["BI","Burundi"],["KH","Cambodia"],["CM","Cameroon"],["CV","Cape Verde"],["KY","Cayman Islands"],["CF","Central African Republic"],["TD","Chad"],["CL","Chile"],["CN","China"],["CX","Christmas Island"],["CC","Cocos (Keeling) Islands"],["CO","Colombia"],["KM","Comoros"],["CG","Congo"],["CK","Cook Islands"],["CR","Costa Rica"],["HR","Croatia (Hrvatska)"],["CU","Cuba"],["CY","Cyprus"],["CZ","Czech Republic"],["DK","Denmark"],["DJ","Djibouti"],["DM","Dominica"],["DO","Dominican Republic"],["TP","East Timor"],["EC","Ecudaor"],["EG","Egypt"],["SV","El Salvador"],["GQ","Equatorial Guinea"],["ER","Eritrea"],["EE","Estonia"],["ET","Ethiopia"],["FK","Falkland Islands (Malvinas)"],["FO","Faroe Islands"],["FJ","Fiji"],["FI","Finland"],["FR","France"],["FX","France, Metropolitan"],["GF","French Guiana"],["PF","French Polynesia"],["TF","French Southern Territories"],["GA","Gabon"],["GM","Gambia"],["GE","Georgia"],["DE","Germany"],["GH","Ghana"],["GI","Gibraltar"],["GR","Greece"],["GL","Greenland"],["GD","Grenada"],["GP","Guadeloupe"],["GU","Guam"],["GT","Guatemala"],["GN","Guinea"],["GW","Guinea-Bissau"],["GY","Guyana"],["HT","Haiti"],["HM","Heard and Mc Donald Islands"],["HN","Honduras"],["HK","Hong Kong"],["HU","Hungary"],["IS","Iceland"],["IN","India"],["ID","Indonesia"],["IR","Iran (Islamic Republic of)"],["IQ","Iraq"],["IE","Ireland"],["IL","Israel"],["IT","Italy"],["CI","Ivory Coast"],["JM","Jamaica"],["JP","Japan"],["JO","Jordan"],["KZ","Kazakhstan"],["KE","Kenya"],["KI","Kiribati"],["KP","Korea, Democratic People's Republic of"],["KR","Korea, Republic of"],["KW","Kuwait"],["KG","Kyrgyzstan"],["LA","Lao People's Democratic Republic"],["LV","Latvia"],["LB","Lebanon"],["LS","Lesotho"],["LR","Liberia"],["LY","Libyan Arab Jamahiriya"],["LI","Liechtenstein"],["LT","Lithuania"],["LU","Luxembourg"],["MO","Macau"],["MK","Macedonia"],["MG","Madagascar"],["MW","Malawi"],["MY","Malaysia"],["MV","Maldives"],["ML","Mali"],["MT","Malta"],["MH","Marshall Islands"],["MQ","Martinique"],["MR","Mauritania"],["MU","Mauritius"],["TY","Mayotte"],["MX","Mexico"],["FM","Micronesia, Federated States of"],["MD","Moldova, Republic of"],["MC","Monaco"],["MN","Mongolia"],["MS","Montserrat"],["MA","Morocco"],["MZ","Mozambique"],["MM","Myanmar"],["NA","Namibia"],["NR","Nauru"],["NP","Nepal"],["NL","Netherlands"],["AN","Netherlands Antilles"],["NC","New Caledonia"],["NZ","New Zealand"],["NI","Nicaragua"],["NE","Niger"],["NG","Nigeria"],["NU","Niue"],["NF","Norfork Island"],["MP","Northern Mariana Islands"],["NO","Norway"],["OM","Oman"],["PK","Pakistan"],["PW","Palau"],["PA","Panama"],["PG","Papua New Guinea"],["PY","Paraguay"],["PE","Peru"],["PH","Philippines"],["PN","Pitcairn"],["PL","Poland"],["PT","Portugal"],["PR","Puerto Rico"],["QA","Qatar"],["RE","Reunion"],["RO","Romania"],["RU","Russian Federation"],["RW","Rwanda"],["KN","Saint Kitts and Nevis"],["LC","Saint Lucia"],["VC","Saint Vincent and the Grenadines"],["WS","Samoa"],["SM","San Marino"],["ST","Sao Tome and Principe"],["SA","Saudi Arabia"],["SN","Senegal"],["SC","Seychelles"],["SL","Sierra Leone"],["SG","Singapore"],["SK","Slovakia"],["SI","Slovenia"],["SB","Solomon Islands"],["SO","Somalia"],["ZA","South Africa"],["GS","South Georgia South Sandwich Islands"],["ES","Spain"],["LK","Sri Lanka"],["SH","St. Helena"],["PM","St. Pierre and Miquelon"],["SD","Sudan"],["SR","Suriname"],["SJ","Svalbarn and Jan Mayen Islands"],["SZ","Swaziland"],["SE","Sweden"],["CH","Switzerland"],["SY","Syrian Arab Republic"],["TW","Taiwan"],["TJ","Tajikistan"],["TZ","Tanzania, United Republic of"],["TH","Thailand"],["TG","Togo"],["TK","Tokelau"],["TO","Tonga"],["TT","Trinidad and Tobago"],["TN","Tunisia"],["TR","Turkey"],["TM","Turkmenistan"],["TC","Turks and Caicos Islands"],["TV","Tuvalu"],["UG","Uganda"],["UA","Ukraine"],["AE","United Arab Emirates"],["GB","United Kingdom"],["UM","United States minor outlying islands"],["UY","Uruguay"],["UZ","Uzbekistan"],["VU","Vanuatu"],["VA","Vatican City State"],["VE","Venezuela"],["VN","Vietnam"],["VG","Virigan Islands (British)"],["VI","Virgin Islands (U.S.)"],["WF","Wallis and Futuna Islands"],["EH","Western Sahara"],["YE","Yemen"],["YU","Yugoslavia"],["ZR","Zaire"],["ZM","Zambia"],["ZW","Zimbabwe"]]
, autoLoad: false
});
var cmCountry = new Ext.grid.ColumnModel([
chkColCountry
, { id: 'Id', header: 'Id', dataIndex: 'Id', width: 40 }
, { id: 'Name', header: 'CountryName', dataIndex: 'Name', width: 460 }
, { id: 'After', header: 'After', dataIndex: 'State.After', hidden: true }
]);
var grdCountries = new Ext.grid.GridPanel({
store: dsCountries
, cm: cmCountry
, plugins: chkColCountry
, enableHdMenu: false
});
var win = new Ext.Window({
layout: 'fit'
, height: 190
, width: 600
, items: [grdCountries]
});
win.show();
<link href="//cdnjs.cloudflare.com/ajax/libs/extjs/3.4.1-1/resources/css/ext-all.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/extjs/3.4.1-1/adapter/ext/ext-base.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/extjs/3.4.1-1/ext-all.js"></script>
Click on the column checkbox (the one on the header) and see the gif that isn't spinning as expected.
Note: I have paging functionality in other places but I won't use it here as the 256 rows are always the same. So I rather lose the check all button than paging this.

The problem is not the use of .defer(), it's that you're doing it at the wrong level. The tight loop over the records is what's causing the freeze, and you aren't actually offloading those UI updates to another thread, you're simply delaying execution of the loop. When the loop kicks off after 50 milliseconds, it's still a tight loop that takes a while to execute.
This is a quick fix that, while not optimal, is probably closer to what you want:
this.grid.getStore().each(function(rec) {
rec.set.defer(1, rec, [this.dataIndex, newValue]);
}, this);
column.renderHeaderCheck();
this.grid.getView().updateHeaders();
A couple of notes. If you are using defer to simply execute code on another thread (and not truly because you need a specific delay) just use 1 ms. No need to wait longer for no reason.
Secondly, beware using defer like this -- it may work for this case, but this is not a general best practice. When you start deferring stuff (especially in a loop like this), it can potentially cause issues if other code executes during the middle of your loop that might also affect your underlying store. Ideally, you'd be able to find a more suitable solution like deferring only the grid's UI update, but I suspect doing so might require an override or two (not sure off the top of my head). So if this solves it for you, great -- but don't say I didn't warn you if some other weird bug pops up later ;)
BTW, if you are scrolled down in the grid, there will still be a noticeable delay to the user since the loop still executes top to bottom. You could get fancy and update the visible records first before moving on to the rest of the data set -- depends on how much effort you want to put into it.
EDIT: OK, after putting a little more thought into this, all you need to do to avoid UI updates is tell the store not to fire its update events during the loop, then manually refresh the grid after all data updates are done. With this approach you shouldn't even need a spinner in the header, and you avoid all the potential issues with defer. Try this:
internalSetAllColumn: function(column, newValue) {
var store = this.grid.getStore(),
gridView = this.grid.getView();
column.masterValue = newValue;
store.suspendEvents();
store.each(function(rec) {
rec.set(this.dataIndex, newValue);
}, this);
store.resumeEvents();
column.renderHeaderCheck();
gridView.refresh();
}

Instead of using defer, trying using Ext.TaskMgr which allows you to create a task and run it in a multithreaded manner.
Example of a task.
var task = {
run: function(){
Ext.fly('clock').update(new Date().format('g:i:s A'));
},
interval: 1000 //1 second
}
Ext.TaskMgr.start(task);

Too tricky probably, but it does show the animated spinning wheel, and seems to work just fine:
internalSetAllColumn: function(column, newValue) {
column.masterValue = newValue;
column.header = '<div class="x-grid3-check-col-td loading-indicator"> </div>'; // loading icon
this.grid.getView().updateHeaders();
var store = this.grid.getStore();
var count = store.getCount();
var step = 5;
var times = (count / step) >> 0;
var task = {
run: function() {
var last = step * task.taskRunCount;
var first = last - step;
if (first <= count) {
var recs = store.getRange(first, last);
Ext.each(recs, function(rec) {
rec.set(this.dataIndex, newValue);
}, this);
}
if (task.taskRunCount > times) {
column.renderHeaderCheck();
this.grid.getView().updateHeaders();
return false;
}
},
interval: 1,
scope: this
};
Ext.TaskMgr.start(task);
}
/*global Ext */
Ext.grid.CheckColumn = function(config){
Ext.apply(this, config);
if(!this.id){
this.id = Ext.id();
}
this.headerText = this.headerText || this.header || ' ';
this.renderer = this.renderer.createDelegate(this);
};
Ext.grid.CheckColumn.prototype = {
init: function(grid) {
this.grid = grid;
var column = this.grid.getColumnModel().getColumnById(this.id);
column.masterValue = false;
if (this.headerCheck) {
column.renderHeaderCheck();
}
this.grid.on('headerclick', this.onHeaderClick, this);
this.grid.on('render', function() {
var view = this.grid.getView();
view.mainBody.on('mousedown', this.onMouseDown, this);
view.updateHeaders();
}, this);
}
, dataIndex: ''
, masterValue: false
, width: 90
, fixed: true
, headerCheck: false
, enableHeaderControl: true
, onMouseDown: function(e, t) {
if (!this.readonly) {
if (Ext.fly(t).hasClass('x-grid3-cc-' + this.id)) {
e.stopEvent();
var editEvent = {};
editEvent.row = this.grid.getView().findRowIndex(t);
editEvent.column = this.grid.getColumnModel().findColumnIndex(this.dataIndex);
editEvent.grid = this.grid;
editEvent.field = this.dataIndex;
editEvent.record = this.grid.store.getAt(editEvent.row);
editEvent.originalValue = editEvent.record.data[this.dataIndex];
editEvent.value = !editEvent.originalValue;
editEvent.record.set(editEvent.field, editEvent.value);
editEvent.grid.fireEvent('afteredit', editEvent);
}
}
},
getCheckedCls: function(v) {
return v === -1 ? 'x-grid3-check-col-gray' : (v ? 'x-grid3-check-col-on' : 'x-grid3-check-col');
},
renderHeaderCheck: function() {
this.header = '<div class="' + this.getCheckedCls(this.masterValue) + '">' + this.headerText + '</div>';
},
onHeaderClick: function(grid, columnIndex, event) {
var colModel = grid.getColumnModel();
var cIndex = colModel.getIndexById(this.id);
if (cIndex == columnIndex && this.enableHeaderControl !== false && this.headerCheck) {
var column = colModel.getColumnById(this.id);
var newValue = !column.masterValue;
this.internalSetAllColumn(column, newValue);
colModel.fireEvent("headerchange", colModel, columnIndex, column.header);
this.grid.getView().updateHeaders();
}
},
renderer: function(v, p, record, rowIndex, colIndex, store) {
p.css += ' x-grid3-check-col-td';
return '<div class="' + this.getCheckedCls(v) + ' x-grid3-cc-' + this.id + '"> </div>';
},
internalSetAllColumn: function(column, newValue) {
column.masterValue = newValue;
column.header = '<div class="x-grid3-check-col-td loading-indicator"> </div>'; // loading icon
this.grid.getView().updateHeaders();
var store = this.grid.getStore();
var count = store.getCount();
var step = 5;
var times = (count / step) >> 0;
var task = {
run: function() {
var last = step * task.taskRunCount;
var first = last - step;
if (first <= count) {
var recs = store.getRange(first, last);
Ext.each(recs, function(rec) {
rec.set(this.dataIndex, newValue);
}, this);
}
if (task.taskRunCount > times) {
column.renderHeaderCheck();
this.grid.getView().updateHeaders();
return false;
}
},
interval: 1,
scope: this
};
Ext.TaskMgr.start(task);
},
setAllColumn: function(columnIndex, newValue) {
var colModel = this.grid.getColumnModel();
var colId = colModel.getColumnId(columnIndex);
var column = colModel.getColumnById(colId);
this.internalSetAllColumn(column, newValue);
this.grid.getView().updateHeaders();
}
};
// -----------------------------------------
// End of plugin - Beginning of example code
// -----------------------------------------
var chkColCountry = new Ext.grid.CheckColumn({ dataIndex: 'State.After', width: 50, headerCheck: true });
var dsCountries = new Ext.data.ArrayStore({
fields: ['Id', 'Name']
, data: [["US","United States"],["CA","Canada"],["AF","Afghanistan"],["AL","Albania"],["DZ","Algeria"],["DS","American Samoa"],["AD","Andorra"],["AO","Angola"],["AI","Anguilla"],["AQ","Antarctica"],["AG","Antigua and/or Barbuda"],["AR","Argentina"],["AM","Armenia"],["AW","Aruba"],["AU","Australia"],["AT","Austria"],["AZ","Azerbaijan"],["BS","Bahamas"],["BH","Bahrain"],["BD","Bangladesh"],["BB","Barbados"],["BY","Belarus"],["BE","Belgium"],["BZ","Belize"],["BJ","Benin"],["BM","Bermuda"],["BT","Bhutan"],["BO","Bolivia"],["BA","Bosnia and Herzegovina"],["BW","Botswana"],["BV","Bouvet Island"],["BR","Brazil"],["IO","British lndian Ocean Territory"],["BN","Brunei Darussalam"],["BG","Bulgaria"],["BF","Burkina Faso"],["BI","Burundi"],["KH","Cambodia"],["CM","Cameroon"],["CV","Cape Verde"],["KY","Cayman Islands"],["CF","Central African Republic"],["TD","Chad"],["CL","Chile"],["CN","China"],["CX","Christmas Island"],["CC","Cocos (Keeling) Islands"],["CO","Colombia"],["KM","Comoros"],["CG","Congo"],["CK","Cook Islands"],["CR","Costa Rica"],["HR","Croatia (Hrvatska)"],["CU","Cuba"],["CY","Cyprus"],["CZ","Czech Republic"],["DK","Denmark"],["DJ","Djibouti"],["DM","Dominica"],["DO","Dominican Republic"],["TP","East Timor"],["EC","Ecudaor"],["EG","Egypt"],["SV","El Salvador"],["GQ","Equatorial Guinea"],["ER","Eritrea"],["EE","Estonia"],["ET","Ethiopia"],["FK","Falkland Islands (Malvinas)"],["FO","Faroe Islands"],["FJ","Fiji"],["FI","Finland"],["FR","France"],["FX","France, Metropolitan"],["GF","French Guiana"],["PF","French Polynesia"],["TF","French Southern Territories"],["GA","Gabon"],["GM","Gambia"],["GE","Georgia"],["DE","Germany"],["GH","Ghana"],["GI","Gibraltar"],["GR","Greece"],["GL","Greenland"],["GD","Grenada"],["GP","Guadeloupe"],["GU","Guam"],["GT","Guatemala"],["GN","Guinea"],["GW","Guinea-Bissau"],["GY","Guyana"],["HT","Haiti"],["HM","Heard and Mc Donald Islands"],["HN","Honduras"],["HK","Hong Kong"],["HU","Hungary"],["IS","Iceland"],["IN","India"],["ID","Indonesia"],["IR","Iran (Islamic Republic of)"],["IQ","Iraq"],["IE","Ireland"],["IL","Israel"],["IT","Italy"],["CI","Ivory Coast"],["JM","Jamaica"],["JP","Japan"],["JO","Jordan"],["KZ","Kazakhstan"],["KE","Kenya"],["KI","Kiribati"],["KP","Korea, Democratic People's Republic of"],["KR","Korea, Republic of"],["KW","Kuwait"],["KG","Kyrgyzstan"],["LA","Lao People's Democratic Republic"],["LV","Latvia"],["LB","Lebanon"],["LS","Lesotho"],["LR","Liberia"],["LY","Libyan Arab Jamahiriya"],["LI","Liechtenstein"],["LT","Lithuania"],["LU","Luxembourg"],["MO","Macau"],["MK","Macedonia"],["MG","Madagascar"],["MW","Malawi"],["MY","Malaysia"],["MV","Maldives"],["ML","Mali"],["MT","Malta"],["MH","Marshall Islands"],["MQ","Martinique"],["MR","Mauritania"],["MU","Mauritius"],["TY","Mayotte"],["MX","Mexico"],["FM","Micronesia, Federated States of"],["MD","Moldova, Republic of"],["MC","Monaco"],["MN","Mongolia"],["MS","Montserrat"],["MA","Morocco"],["MZ","Mozambique"],["MM","Myanmar"],["NA","Namibia"],["NR","Nauru"],["NP","Nepal"],["NL","Netherlands"],["AN","Netherlands Antilles"],["NC","New Caledonia"],["NZ","New Zealand"],["NI","Nicaragua"],["NE","Niger"],["NG","Nigeria"],["NU","Niue"],["NF","Norfork Island"],["MP","Northern Mariana Islands"],["NO","Norway"],["OM","Oman"],["PK","Pakistan"],["PW","Palau"],["PA","Panama"],["PG","Papua New Guinea"],["PY","Paraguay"],["PE","Peru"],["PH","Philippines"],["PN","Pitcairn"],["PL","Poland"],["PT","Portugal"],["PR","Puerto Rico"],["QA","Qatar"],["RE","Reunion"],["RO","Romania"],["RU","Russian Federation"],["RW","Rwanda"],["KN","Saint Kitts and Nevis"],["LC","Saint Lucia"],["VC","Saint Vincent and the Grenadines"],["WS","Samoa"],["SM","San Marino"],["ST","Sao Tome and Principe"],["SA","Saudi Arabia"],["SN","Senegal"],["SC","Seychelles"],["SL","Sierra Leone"],["SG","Singapore"],["SK","Slovakia"],["SI","Slovenia"],["SB","Solomon Islands"],["SO","Somalia"],["ZA","South Africa"],["GS","South Georgia South Sandwich Islands"],["ES","Spain"],["LK","Sri Lanka"],["SH","St. Helena"],["PM","St. Pierre and Miquelon"],["SD","Sudan"],["SR","Suriname"],["SJ","Svalbarn and Jan Mayen Islands"],["SZ","Swaziland"],["SE","Sweden"],["CH","Switzerland"],["SY","Syrian Arab Republic"],["TW","Taiwan"],["TJ","Tajikistan"],["TZ","Tanzania, United Republic of"],["TH","Thailand"],["TG","Togo"],["TK","Tokelau"],["TO","Tonga"],["TT","Trinidad and Tobago"],["TN","Tunisia"],["TR","Turkey"],["TM","Turkmenistan"],["TC","Turks and Caicos Islands"],["TV","Tuvalu"],["UG","Uganda"],["UA","Ukraine"],["AE","United Arab Emirates"],["GB","United Kingdom"],["UM","United States minor outlying islands"],["UY","Uruguay"],["UZ","Uzbekistan"],["VU","Vanuatu"],["VA","Vatican City State"],["VE","Venezuela"],["VN","Vietnam"],["VG","Virigan Islands (British)"],["VI","Virgin Islands (U.S.)"],["WF","Wallis and Futuna Islands"],["EH","Western Sahara"],["YE","Yemen"],["YU","Yugoslavia"],["ZR","Zaire"],["ZM","Zambia"],["ZW","Zimbabwe"]]
, autoLoad: false
});
var cmCountry = new Ext.grid.ColumnModel([
chkColCountry
, { id: 'Id', header: 'Id', dataIndex: 'Id', width: 40 }
, { id: 'Name', header: 'CountryName', dataIndex: 'Name', width: 460 }
, { id: 'After', header: 'After', dataIndex: 'State.After', hidden: true }
]);
var grdCountries = new Ext.grid.GridPanel({
store: dsCountries
, cm: cmCountry
, plugins: chkColCountry
, enableHdMenu: false
});
var win = new Ext.Window({
layout: 'fit'
, height: 190
, width: 600
, items: [grdCountries]
});
win.show();
<link href="//cdnjs.cloudflare.com/ajax/libs/extjs/3.4.1-1/resources/css/ext-all.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/extjs/3.4.1-1/adapter/ext/ext-base.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/extjs/3.4.1-1/ext-all.js"></script>

Related

How can I retrieve the cursor position in an ExtJS text area field?

I defined a text area field in an extJS window as follows:
me.myTextArea = Ext.create({
xtype: 'textareafield',
width: 500,
height: 500,
editable: true,
selectOnFocus: false,
listeners: {
afterrender: function() {
this.focus(true);
let cursorPos = this.getValue().length;
this.selectText(cursorPos, cursorPos);
}
}
});
I added the text area field to a panel contained within a window, and I set the text area field as focus element. I prevented the text there to be selected after the textarea field's being rendered. I would like to add the following feature. On closing the window, I will be able to get the position the cursor has within the text area field. So far, my attemps at resolving the problem were withou success. I set up an alert as follows:
listeners: {
'close': function(me) {
alert(me.getCaretPos(cmp.myTextArea.getEl().getId()));
}
},
Now the function named "getCaretPos" is designed to get the cursor position. I did not invent the function, but I found in on the net. Haplessly, the function does not work, it always returns -1:
getCaretPos: function(id){
var el = document.getElementById(id);
var rng, ii=-1;
if(typeof el.selectionStart=="number") {
ii=el.selectionStart;
} else if (document.selection && el.createTextRange){
rng=document.selection.createRange();
rng.collapse(true);
rng.moveStart("character", -el.value.length);
ii=rng.text.length;
}
return ii;
}
Especially, I do not undertsand, why "el.selectionStart" is always undefined in the function. I would be very glad if somebody could help me in resolving this mystery.
In this FIDDLE, I have created a custometextarea using extend:Ext.form.field.TextArea and putted some custom method. I hope this will help/guide you to achieve your requirements.
I have checked this code is working in ExtJS 4.x and later.
CODE SNIPPET
Ext.application({
name: 'Fiddle',
launch: function () {
Ext.define('CustomeTextArea', {
extend: 'Ext.form.field.TextArea',
xtype: 'customtextarea',
inputTypeSelectionSupported: /text|password|search|tel|url/i,
selectDir: {
b: 'backward',
back: 'backward',
f: 'forward'
},
/*
* this event will call get the cursoe postion inside of field
* #return {NUMBER}
*/
getCaretPos: function () {
var dom = this.inputEl.dom,
pos, selection;
if (this.inputTypeSelectionSupported.test(dom.type)) {
pos = dom.selectionStart;
selection = (typeof pos !== 'number') && this.getTextSelection();
if (selection) {
pos = selection[0];
}
} else {
Ext.raise('Input type of "' + dom.type + '" does not support selectionStart');
}
return pos;
},
/*
* this event will call selectText event
* #params {NUMBER} pos
*/
setCaretPos: function (pos) {
this.selectText(pos, pos);
},
/*
* #params {NUMBER} start
* #params {NUMBER} end
* #params {STRING} direction to select it is optional
*/
selectText: function (start, end, direction) {
var me = this,
range,
dom = me.inputEl.dom,
len;
if (dom && me.inputTypeSelectionSupported.test(dom.type)) {
start = start || 0;
len = dom.value.length;
if (end === undefined) {
end = len;
}
direction = me.selectDir[direction] || direction || 'forward';
if (dom.setSelectionRange) {
dom.setSelectionRange(start, end, direction);
} else if (dom.createTextRange) {
range = dom.createTextRange();
range.moveStart('character', start);
range.moveEnd('character', -(len - end));
range.select();
}
} else if (!me.inputTypeSelectionSupported.test(dom.type)) {
Ext.raise('Input type of "' + dom.type + '" does not support setSelectionRange');
}
return me;
},
//This event will select the text inside of textfield/textarea
getTextSelection: function () {
var dom = this.inputEl.dom;
if (this.inputTypeSelectionSupported.test(dom.type)) {
return [
dom.selectionStart,
dom.selectionEnd,
dom.selectionDirection
];
} else {
Ext.raise('Input type of "' + this.dom.type + '" does not support selectionStart, selectionEnd and selectionDirection');
return [];
}
}
});
Ext.create('Ext.window.Window', {
title: 'cursor position',
height: 200,
width: 400,
layout: 'fit',
items: [{
xtype: 'customtextarea',
margin: 5,
grow: true,
name: 'message',
fieldLabel: 'Message',
labelAlign: 'top',
value: 'How can I retrieve the cursor position in an ExtJS text area field?',
anchor: '100%',
listeners: {
afterrender: function (cmp) {
Ext.defer(function () {
cmp.focus(false); //if you pass true then it will automatically select text inside of field
let cursorPos = cmp.getValue().length;
cmp.selectText(0, cursorPos - 5, 'b');
}, 50)
}
}
}],
listeners: {
beforeclose: function (win) {
var textArea = win.down('customtextarea'),
pos = textArea.getCaretPos();
Ext.Msg.alert('Success', `This is your cursor postion <b>${pos}</b>`)
}
}
}).show();
}
});

ToolTip in Grid cell - ExtJs 6

I am using below code to display Tool Tip for Grid cell In ExtJS 6
{
header: 'Name',
cls: 'nameCls',
locked: true,
tdCls: 'nameTdCls',
dataIndex: 'name',
renderer: function (value, metaData, record, rowIndex, colIndex, store, view) {
metaData.tdAttr = 'data-qtip= "' + value + '" data-qclass="tipCls" data-qwidth=200';
return value;
}}
When i run the application it doesnt show the tooltip and display below error message.
Any idea guys??
Thanks in advance guys.
Regards,
Mahendra
Have you tried creating an Ext.tip.ToolTip? You can create a single one to serve as tooltip for each name cell (using delegate) and update it with the value of that cell. Set up a grid render listener to create the tooltip like this:
render: function(grid) {
var view = grid.getView();
grid.tip = Ext.create('Ext.tip.ToolTip', {
target: view.getId(),
delegate: view.itemSelector + ' .nameTdCls',
trackMouse: true,
listeners: {
beforeshow: function updateTipBody(tip) {
var tipGridView = tip.target.component;
var record = tipGridView.getRecord(tip.triggerElement);
tip.update(record.get('name'));
}
}
});
}
For a working example, see this Fiddle.
Thanks for Robert Klein Kromhof!
grid columns:
columns: [{..., tdCls: 'tip'}]
grid listeners:
render: function (grid) {
var view = grid.getView();
grid.tip = Ext.create('Ext.tip.ToolTip', {
target: view.getId(),
delegate: view.itemSelector + ' .tip',
trackMouse: true,
listeners: {
beforeshow: function (tip) {
var tipGridView = tip.target.component;
var record = tipGridView.getRecord(tip.triggerElement);
var colname = tipGridView.getHeaderCt().getHeaderAtIndex(tip.triggerElement.cellIndex).dataIndex;
tip.update(record.get(colname));
}
}
});
},
destroy: function (view) {
delete view.tip;
}
Create independent function and call when you need.
var grid = Ext.getCmp('your_grid_id'); // Enter your grid id
initToolTip(grid); // call function
initToolTip: function(grid) {
var view = grid.view;
// record the current cellIndex
grid.mon(view, {
uievent: function(type, view, cell, recordIndex, cellIndex, e) {
grid.cellIndex = cellIndex;
grid.recordIndex = recordIndex;
}
});
grid.tip = Ext.create('Ext.tip.ToolTip', {
target: view.el,
delegate: '.x-grid-cell',
trackMouse: true,
renderTo: Ext.getBody(),
listeners: {
beforeshow: function updateTipBody(tip) {
if (!Ext.isEmpty(grid.cellIndex) && grid.cellIndex !== -1) {
header = grid.headerCt.getGridColumns()[grid.cellIndex];
columnText = grid.getStore().getAt(grid.recordIndex).get(header.dataIndex);
tip.update(columnText);
}
}
}
});
}

Need solution for Multi Select in Extjs tree

Am complete stranger to Extjs. I have a requirement to allow multi select in the Extjs tree. Below piece of code is doing single select. i need to change the code to make it multi select with semi-colon between selected ids. Can anyone please change the code as per the requirement. Also if you could tell me to which field or variable the selected value of the tree is written into. Thanks in advance
Ext.onReady(function() {
Ext.QuickTips.init();
var str='';
var switch_flag = '';
var approvals = '';
var active_mode = '';
var json = null;
Ext.Ajax.request({
url: 'Dmscategorytree/ajax/Message',
method: 'POST',
params:{
lifecycle_id: str,
switch_flag: switch_flag,
approvals: approvals,
active_mode: active_mode
},
success: function(response, options) {
var path='';
var id='';
var text='';
json=response.responseText;
alert(json);
json = json.replace(/"/g,'\"');
json=Ext.util.JSON.decode(json);
var flag=true;
var myloader = new Ext.tree.TreeLoader();
myloader.load = function(node, cb,scope) {
if(this.clearOnLoad){
while(node.firstChild){
node.removeChild(node.firstChild);
}
}
if(this.doPreload(node)){
this.runCallback(cb, scope || node, [node]);
}
cb();
}
var tree = new Ext.tree.TreePanel({
animate:true,
autoScroll:true,
//loader: new Tree.TreeLoader({dataUrl:'get-nodes.php'}),
containerScroll: true,
border: false,
loader:myloader,
rootVisible: false,
listeners:{
checkchange:function(node){
if(flag){
toggleCheck(tree.root,false,node.id);
path=node.attributes.value;
id=node.attributes.ID;
text=node.attributes.text;
path=path.replace(/\^/g,'/');
}
}
}
});
function SelectToParent()
{
try
{
parent.window.opener.callParent(path,id);
parent.window.opener.focus();
parent.window.close();
}
catch(e){
alert('got exception');
window.close();
}
}
function toggleCheck(node,isCheck,nodeId)
{
flag=false;
if(node)
{
var args=[isCheck];
node.cascade(function(){
c=args[0];
if(nodeId!=this.id){
this.ui.toggleCheck(c);
this.attributes.checked=c;
}
},null,args);
}
flag=true;
return true;
}
var root = new Ext.tree.AsyncTreeNode({
text: 'Ext JS',
draggable:false, // disable root node dragging
id:'src',
children: json
});
tree.setRootNode(root);
var topbar = new Ext.Toolbar({
region : 'north',
height:30,
margins: '0 0 0 5',
items:[
{
xtype: 'box',
id: 'title',
autoEl: {
html: '#label.chooseCat#'
}
,width:525
},
{
text: '#label.Done#',
id: 'doneBtn',
tooltip: 'Done',
handler: SelectToParent
}
]
});
topbar.render('tree');
tree.render('tree');
tree.getRootNode().expand();
}
});
});
Please refer the following links,
pass two id s in extjs 4 tree multiSelect and pass one id in single click
Multiselect Tree & Drag and Drop
Drag and Drop between Grid and “multiselect” control in EXTJS
Demo

Go back to the selection in Data Grid after reloading the page ExtJS 4.1 [duplicate]

I have a problem. I use extjs grid. This grid will be refreshed every seconds.
I refresh with this function:
ND.refresh = function() {
ND.commList.load();
}
var refreshSeconds = refreshRate * 1000;
var t = setInterval('ND.refresh()', refreshSeconds);
But when someone selected a row to highlight it it reset this selection.
How can I remember the selected row and highlight it again after refresh?
This is my grid:
var grid = Ext.create('Ext.grid.Panel', {
autoscroll: true,
region: 'center',
store: ND.dashBoardDataStore,
stateful: true,
forceFit: true,
loadMask: false,
stateId: 'stateGrid',
viewConfig: {
stripeRows: true
},
columns: [{
text: 'Vehicle',
sortable: true,
flexible: 1,
width: 60,
dataIndex: 'vehicle'
}, {
text: 'CCU',
sortable: true,
flexible: 0,
width: 50,
renderer: status,
dataIndex: 'ccuStatus'
}]
});
Thanks guys
I wrote simple Ext.grid.Panel extension that automatically selects back rows that were selected before store reload. You can try it in this jsFiddle
Ext.define('PersistantSelectionGridPanel', {
extend: 'Ext.grid.Panel',
selectedRecords: [],
initComponent: function() {
this.callParent(arguments);
this.getStore().on('beforeload', this.rememberSelection, this);
this.getView().on('refresh', this.refreshSelection, this);
},
rememberSelection: function(selModel, selectedRecords) {
if (!this.rendered || Ext.isEmpty(this.el)) {
return;
}
this.selectedRecords = this.getSelectionModel().getSelection();
this.getView().saveScrollState();
},
refreshSelection: function() {
if (0 >= this.selectedRecords.length) {
return;
}
var newRecordsToSelect = [];
for (var i = 0; i < this.selectedRecords.length; i++) {
record = this.getStore().getById(this.selectedRecords[i].getId());
if (!Ext.isEmpty(record)) {
newRecordsToSelect.push(record);
}
}
this.getSelectionModel().select(newRecordsToSelect);
Ext.defer(this.setScrollTop, 30, this, [this.getView().scrollState.top]);
}
});
The straightforward solution is just save somewhere in js index of selected row. Then after reload you could easily select this row by index using grid's selection model.
Get selection model: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.grid.Panel-method-getSelectionModel
var selectionModel = grid.getSelectionModel()
Get selected rows: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.selection.Model-method-getSelection
var selection = selectionModel.getSelection()
Set selected row back: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.selection.Model-method-select
selectionModel.select(selection)
Here is another way to select the previously selected record:
var selectionModel = grid.getSelectionModel()
// get the selected record
var selectedRecord = selectionModel.getSelection()[0]
// get the index of the selected record
var selectedIdx = grid.store.indexOfId(selectedRecord.data.id);
// select by index
grid.getSelectionModel().select(selectedIdx);
For some reason the grid.getSelectionModel().select(record) method wasn't working for me, but selecting by index seems to work.
Edit: found out why grid.getSelectionModel().select(record) method wasn't working. Apparently the store is reloaded, the record instances aren't the same (they have different automatically generated Ext IDs). You have to use selectAt() in this case.
for extjs 4.1.7 users
need a workarround about the statement in
refreshSelection() {
...
Ext.defer(this.setScrollTop, 30, this,
[this.getView().scrollState.top])
}
thus setScrollTop no longer exists
so a working soluction is add
me.getView().preserveScrollOnRefresh = true;
in initComponent
Ext.define('PersistantSelectionGridPanel', {
extend: 'Ext.grid.Panel',
selectedRecords: [],
initComponent: function() {
this.callParent(arguments);
this.getStore().on('beforeload', this.rememberSelection, this);
this.getView().on('refresh', this.refreshSelection, this);
//-------------------------------------------
me.getView().preserveScrollOnRefresh = true;
//-------------------------------------------
},
rememberSelection: function(selModel, selectedRecords) {
if (!this.rendered || Ext.isEmpty(this.el)) {
return;
}
this.selectedRecords = this.getSelectionModel().getSelection();
this.getView().saveScrollState();
},
refreshSelection: function() {
if (0 >= this.selectedRecords.length) {
return;
}
var newRecordsToSelect = [];
for (var i = 0; i < this.selectedRecords.length; i++) {
record = this.getStore().getById(this.selectedRecords[i].getId());
if (!Ext.isEmpty(record)) {
newRecordsToSelect.push(record);
}
}
this.getSelectionModel().select(newRecordsToSelect);
}
});
i have make modification on this code.
If you make selection, and aplys a filter on the store and reload it, the selection model have a first empty array in this selected collection ( at index 0 ).
This modification is in the last line of the "refreshSelection" function.
if (newRecordsToSelect.length >= 1){
this.getSelectionModel().select(newRecordsToSelect);
Ext.defer(this.setScrollTop, 30, this, [this.getView().scrollState.top]);
}

remember after refresh selected row in extjs grid

I have a problem. I use extjs grid. This grid will be refreshed every seconds.
I refresh with this function:
ND.refresh = function() {
ND.commList.load();
}
var refreshSeconds = refreshRate * 1000;
var t = setInterval('ND.refresh()', refreshSeconds);
But when someone selected a row to highlight it it reset this selection.
How can I remember the selected row and highlight it again after refresh?
This is my grid:
var grid = Ext.create('Ext.grid.Panel', {
autoscroll: true,
region: 'center',
store: ND.dashBoardDataStore,
stateful: true,
forceFit: true,
loadMask: false,
stateId: 'stateGrid',
viewConfig: {
stripeRows: true
},
columns: [{
text: 'Vehicle',
sortable: true,
flexible: 1,
width: 60,
dataIndex: 'vehicle'
}, {
text: 'CCU',
sortable: true,
flexible: 0,
width: 50,
renderer: status,
dataIndex: 'ccuStatus'
}]
});
Thanks guys
I wrote simple Ext.grid.Panel extension that automatically selects back rows that were selected before store reload. You can try it in this jsFiddle
Ext.define('PersistantSelectionGridPanel', {
extend: 'Ext.grid.Panel',
selectedRecords: [],
initComponent: function() {
this.callParent(arguments);
this.getStore().on('beforeload', this.rememberSelection, this);
this.getView().on('refresh', this.refreshSelection, this);
},
rememberSelection: function(selModel, selectedRecords) {
if (!this.rendered || Ext.isEmpty(this.el)) {
return;
}
this.selectedRecords = this.getSelectionModel().getSelection();
this.getView().saveScrollState();
},
refreshSelection: function() {
if (0 >= this.selectedRecords.length) {
return;
}
var newRecordsToSelect = [];
for (var i = 0; i < this.selectedRecords.length; i++) {
record = this.getStore().getById(this.selectedRecords[i].getId());
if (!Ext.isEmpty(record)) {
newRecordsToSelect.push(record);
}
}
this.getSelectionModel().select(newRecordsToSelect);
Ext.defer(this.setScrollTop, 30, this, [this.getView().scrollState.top]);
}
});
The straightforward solution is just save somewhere in js index of selected row. Then after reload you could easily select this row by index using grid's selection model.
Get selection model: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.grid.Panel-method-getSelectionModel
var selectionModel = grid.getSelectionModel()
Get selected rows: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.selection.Model-method-getSelection
var selection = selectionModel.getSelection()
Set selected row back: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.selection.Model-method-select
selectionModel.select(selection)
Here is another way to select the previously selected record:
var selectionModel = grid.getSelectionModel()
// get the selected record
var selectedRecord = selectionModel.getSelection()[0]
// get the index of the selected record
var selectedIdx = grid.store.indexOfId(selectedRecord.data.id);
// select by index
grid.getSelectionModel().select(selectedIdx);
For some reason the grid.getSelectionModel().select(record) method wasn't working for me, but selecting by index seems to work.
Edit: found out why grid.getSelectionModel().select(record) method wasn't working. Apparently the store is reloaded, the record instances aren't the same (they have different automatically generated Ext IDs). You have to use selectAt() in this case.
for extjs 4.1.7 users
need a workarround about the statement in
refreshSelection() {
...
Ext.defer(this.setScrollTop, 30, this,
[this.getView().scrollState.top])
}
thus setScrollTop no longer exists
so a working soluction is add
me.getView().preserveScrollOnRefresh = true;
in initComponent
Ext.define('PersistantSelectionGridPanel', {
extend: 'Ext.grid.Panel',
selectedRecords: [],
initComponent: function() {
this.callParent(arguments);
this.getStore().on('beforeload', this.rememberSelection, this);
this.getView().on('refresh', this.refreshSelection, this);
//-------------------------------------------
me.getView().preserveScrollOnRefresh = true;
//-------------------------------------------
},
rememberSelection: function(selModel, selectedRecords) {
if (!this.rendered || Ext.isEmpty(this.el)) {
return;
}
this.selectedRecords = this.getSelectionModel().getSelection();
this.getView().saveScrollState();
},
refreshSelection: function() {
if (0 >= this.selectedRecords.length) {
return;
}
var newRecordsToSelect = [];
for (var i = 0; i < this.selectedRecords.length; i++) {
record = this.getStore().getById(this.selectedRecords[i].getId());
if (!Ext.isEmpty(record)) {
newRecordsToSelect.push(record);
}
}
this.getSelectionModel().select(newRecordsToSelect);
}
});
i have make modification on this code.
If you make selection, and aplys a filter on the store and reload it, the selection model have a first empty array in this selected collection ( at index 0 ).
This modification is in the last line of the "refreshSelection" function.
if (newRecordsToSelect.length >= 1){
this.getSelectionModel().select(newRecordsToSelect);
Ext.defer(this.setScrollTop, 30, this, [this.getView().scrollState.top]);
}

Resources