问题
In the documentation of XTemplate, {#} can be used to get the current array index.
When I use it in the itemTpl of an xlist, I always get 1 instead of the index:
{
xtype: 'list',
store: 'myStore',
itemTpl:new Ext.XTemplate(
'<tpl for=".">',
'<div>Item n°{#1}</div>',
'</tpl>'
),
}
always produces "Item n°1" even if my store contains several items.
Am I doing something wrong ?
回答1:
Note that you're using a Ext.List which fetchs data from a Ext.data.Store, not an Array, so XTemplate processes only 1 item at one time. That's why the {#} (also called xindex) always return 1.
A suggest to work-around this is to set manually the index of items in your store once it's loaded, like this: (listener for your Store)
listeners: {
load: function(store, records){
store.each(function(record, index){
record.set('index', index);
},
store
);
}
Hope it helps.
回答2:
I ran into the same problem and I came up with this:
itemTpl: [
'<div class="item">' +
'Number {[this.getIndex()]}' +
'</div>',
{
getIndex: function() {
return document.getElementsByClassName('item').length + 1;
}
}
]
I prefer this solution than adding extra properties to the store.
And btw, you don't need to put <tpl for="."></tpl>
in itemTpl, it's implicit.
回答3:
This is "as designed" since you are not looping on a record/array here. The template is instantiated once for each element of the store.
See also http://www.sencha.com/forum/showthread.php?179728-Autonumber-in-Template-in-DataView
回答4:
I ran into the same problem, ran into this thread & thought there should be a better solution. After looking into the code of DataView, I noticed the following overridable method :
prepareData: function(data, index, record) {
return data;
}
So there is an index, you only need to add a little override :). I prefer this quick solution, adding the index to my dataobject and overriding a method which is provided for overriding purposes.
Ext.define('MyApp.overrides.dataview.DataView', {
override: 'Ext.dataview.DataView',
prepareData: function(data, index, record) {
if(Ext.isObject(data)) {
data.xindex = index + 1;
}
return data;
}
});
来源:https://stackoverflow.com/questions/10075394/sencha-touch-2-getting-item-index-in-itemtpl