I have made a simple class for icons only. Given a image in which a group of icons lay in one and only row, pass the url of this image and width of each icon to new IconGroup. It will detect the height.
Every icon must have a name for reference, especially useful to toolbar icons. Define the names in IconGroup.aIconIndex in strict sequence.
When the image is loaded, this IconGroup will call listener 'on.Ready' (my style).
Hope Ext team will release a better and official edition of such class.
HTML Code:
<style>
.icon{
border: 1px solid blue;
}
</style>
<script type="text/javascript" src="http://extjs.com/deploy/ext/adapter/yui/yui-utilities.js"></script>
<script type="text/javascript" src="http://extjs.com/deploy/ext/adapter/yui/ext-yui-adapter.js"></script>
<script type="text/javascript" src="http://extjs.com/deploy/ext/ext-all.js"></script>
<script type="text/javascript">
function IconGroup(sUrl, nWidth, imgICON, sClassName){
var _this = this;
/* API in */
_this.aIconIndex = [];
/* listener */
_this.on = {
Ready: function(){}
};
/* global */
var nNaturalWidth, nHeight, nLength;
/* initiate */
var imgCache = new Image();
imgCache.src = sUrl;
Ext.EventManager.addListener(imgCache, 'load', function (){
nNaturalWidth = imgCache.naturalWidth;
nHeight = imgCache.naturalHeight;
nLength = nNaturalWidth / nWidth;
if(imgICON){
for(var i = 0; i < _this.aIconIndex.length; i++){
imgICON[_this.aIconIndex[i]] = get(i);
}
}
_this.on.Ready();
});
/* function */
function get(nIndex){
if(nIndex >= nLength){
console.error('nIndex ' + nIndex + 'is too big!');///
}
var img = new Image();
img.src = Ext.BLANK_IMAGE_URL;
img.className = sClassName;
img = Ext.get(img);
img.setWidth(nWidth);
img.setHeight(nHeight);
img.setStyle({
backgroundImage: 'url(' + sUrl + ')',
backgroundPosition: -(nIndex * nWidth)
});
return img;
}//get
/* API out */
_this.get = get;
}
Ext.onReady(function (){
var sUrl = 'http://code.google.com/images/code_sm.png';
var imgICON = {};//to be filled with img Elements
var oIconGroup = new IconGroup(sUrl, 60, imgICON, 'icon');
oIconGroup.aIconIndex = ['a', 'b', 'C', 'D', 'E'];//Define names for reference
oIconGroup.on.Ready = function(){
document.body.innerHTML = '<h1>Here are icons: 0-a, 1-b, 0-a, 3-D, 2-C</h1>';
oIconGroup.get(0).appendTo(document.body);//0-a
imgICON.b.appendTo(document.body);//1-b
imgICON.a.appendTo(document.body);//0-a
oIconGroup.get(3).appendTo(document.body);//3-D
imgICON['C'].appendTo(document.body);//2-C
};
});
</script>