Question

I have ExtJS Dataview with following template for its Items.

<div class="item-container">
    <div class="{itemCls}"></div>
    <span class="item-title">{title}</span>
</div>

Now, I have set selectedItemCls config with value item-selected, which is styled accordingly in my stylesheet. When I click on items in dataview, it works fine, and selected item is highlighted. But I want to have first item of my dataview be selected by default (and thus having item-selected class already added to it).

I tried to play around the dataview component in its afterrender event but I couldn't add active class to first item.

Update

Note that I want to maintain that toggle behavior of class, so when dataview is rendered and user clicks on other item, first item (on which tab-selected was added programmatically) is no longer highlighted and clicked item gets tab-selected class.

So far, I tried calling dataview.selModel.select(dataview.Store.getAt(0)) within afterrender event, and surprisingly, it works while debugging (breaking execution in afterrender event and proceeding step-by-step) but it throws Uncaught TypeError: Cannot call method 'addCls' of null if I try it without DevTools open. I believe it is due to event bubbling since select() also fires itemclick and selectionchange events internally (I might be wrong though).

P.S. Using Chrome for debugging.

How to attain this?

Was it helpful?

Solution 2

After hacking around for more than an hour, I found the fix!

When using afterrender event, where DataView is technically not fully rendered on UI, calling select() will fire itemclick event but there's nothing on UI, so it would lead to the TypeError I was getting (I'm still not 100% sure if this is the exact reason for TypeError I got).

So I have two possible fixes for this, where I'd prefer 2nd fix.

Option - 1

Make called to select() deferred by a few Milliseconds.

listeners: {
    afterrender: function(dv) {
        Ext.defer(function() {
            dv.selModel.select(dv.store.getAt(0));
        }, 10); // Some small number for delay will do.
    }
}

Option - 2 (Recommended)

Use viewready event instead of afterrender.

listeners: {
    viewready: function(dv) {
        dv.selModel.select(dv.store.getAt(0));
    }
}

I've used 2nd option and it works perfectly, however, any better suggestion is welcome.

OTHER TIPS

Try this:

new Ext.XTemplate(
    '<tpl for=".">',
        '<div class="item-container {[xindex === 1 ? "item-selected" : ""]}">',
            '<div class="{itemCls}"></div>',
            '<span class="item-title">{title}</span>',
        '</div>'
    '</tpl>,
)

You could also try this:

listeners: {
    afterrender: function(dv) {
        dv.selModel.select(dv.store.getAt(0));
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top