seba_sencha
seba_sencha

Reputation: 205

Creating a simple Sencha component using a loop

How do we substitute hard-coded data with a for-loop in Sencha ExtJS?
Say, for example I've defined the following list:

Ext.application({  

    launch: function() {

        Ext.create('Ext.List', {
            fullscreen: true,
            itemTpl: '{title}',
            data: [{
                title: 'Item 1'
            }, {
                title: 'Item 2'
            }, {
                title: 'Item 3'
            }, {
                title: 'Item 4'
            }]
        });      
    }
});

How to replace data to something like this:

Ext.application({
    launch: function() {

       Ext.create('Ext.List', {
            fullscreen: true,
            itemTpl: '{title}',
            data: [
               for(int i=0;i<5;i++){
                  {title: 'Item '+i}, 
               }
              ]
        });

    }
});

Upvotes: 1

Views: 489

Answers (1)

Emissary
Emissary

Reputation: 10148

This is really basic stuff - I'd recommend you familiarise yourself with the basic language constructs before investing time in a framework. There are several ways you could do this...

see: MDN: A re-introduction to Javascript


Simplest way, create your configuration data first and assign it to a variable:

Ext.application({
    launch: function() {

        var listData = [];
        for(var i=0;i<5;i++) 
            listData.push({title: 'Item '+i});

        Ext.create('Ext.List', {
            // ...
            data: listData
        });
    }
});

... or for those times when you're in the global execution scope and you don't want to pollute the window object with unnecessary variables - or just have an OCD over "one-liners" - you could take advantage of an inline function / closure:

Ext.create('Ext.List', {
    // ...
    data: (function(){
        var data = [];
        for(var i=0;i<5;i++) 
            data.push({title: 'Item '+i});
        return data;
    })()
});

... or on occasion I've used the following because I think it looks neater (but that's subjective):

Ext.create('Ext.List', {
    // ...
    data: Ext.Array.map(Array.apply(null, Array(5)), function(o,i){
        return {title: 'Item '+i};
    })
});

Upvotes: 1

Related Questions