Sencha touch 2 : getting item index in itemTpl

亡梦爱人 提交于 2019-12-03 08:42:18

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.

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.

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

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;
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!