Reputation: 20970
I'm working on a prototype of an image gallery in extjs 6.
I've got the basic layout setup in a fiddle, but I'm not sure how (or if I can) add a click listener to each of the tiles in the gallary.
Ext.define('ChrisAndRuthie.view.Viewport',{
extend: 'Ext.container.Viewport',
controller: 'viewportcontroller',
viewModel:{
type: 'viewportmodel'
},
layout: 'border',
items:[
{
region: 'north',
xtype: 'panel',
title: 'chrisandruthie.com',
tools:[
{
xtype: 'button',
text: 'Log In'
},
{
xtype: 'button',
text: 'Log out'
}
]
},
{
region: 'center',
title: 'Content',
header: false,
layout: 'fit',
items:[
{
xtype: 'component',
bodyPadding: 10,
tpl: [
'<tpl for=".">',
'<div class="pic-tile">',
'<div><img src="{image}"></div> ',
'<div>{name}</div>',
'</div>',
'</tpl>'
],
bind:{
data: '{thumbnails}'
}
}
]
}
]
});
Ext.define('ChrisAndRuthie.view.ViewportModel',{
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.viewportmodel',
data: {
thumbnails: [
{
name: 'tumb 1',
image: 'images/image1.png'
},
{
name: 'thumb 2',
image: 'images/image2.png'
},
{
name: 'tumb 3',
image: 'images/image3.png'
},
{
name: 'thumb 4',
image: 'images/image4.png'
}
]
}
});
Ext.define('ChrisAndRuthie.view.ViewportController',{
extend: 'Ext.app.ViewController',
alias: 'controller.viewportcontroller'
});
Ext.application({
name : 'Fiddle',
launch : function() {
Ext.create('ChrisAndRuthie.view.Viewport');
}
});
.pic-tile {
float: left;
padding: 8px;
margin: 8px 8px 4px 8px;
border: 1px solid #4E8FD5;
word-wrap: break-word;
width:200px;
height: 200px;
img {
border: 1px solid #336394;
margin: 0 auto;
width: 100%;
}
}
I used an xtemplate after looking at the dataview kitchen sink example. I like this approach because the tiles will automatically re-arrange themselves into the appropriate number of rows/columns on a window resize (which I haven't found a way to do with any of the built in layouts).
What I'm not able to do is add event listeners to the items generated by the template. I'd like to add a click listener so that I can trigger a window and show the full size image.
Is it possible to add listeners to items rendered in a for loop of an xtemplate? If so, how would I do it?
Thanks!
Upvotes: 1
Views: 748
Reputation: 3734
There is no need to add listeners to each tile individually. Do it on the tile container (the component holding your tile template) with the delegate
option:
listeners: {
click: function(event, tile) {
console.log(tile);
},
element: 'el',
delegate: 'div.pic-tile'
}
The click event will be listened to on the container dom element, but Ext JS will be smart enough to deal with bubbling/capturing and only report clicks on the tiles.
By the way, I'd recommend using dataview
like in the example you cited. It offers built-in item-related events already, like itemclick
and more.
Upvotes: 2