PDA

View Full Version : Binding events to items within a template



ncooley527
29 Dec 2010, 12:27 PM
Hey all --

I've been digging for a while about this, but maybe I'm looking in the wrong place. Curious to know if there is any way to bind events to items that are rendered with templates. For example, consider the following template:



var tpl = new Ext.XTemplate(
'<table>',
'<tpl for=".">',
'<tr><td class="action1">{action1's rendered text}</td></tr>',
'<tr><td class="action2">{action2's rendered text}</td></tr>',
'</tpl>',
'</table>'
)


If rendered in a Dataview, for example, is there a way to have a separate "itemTap" behaviors for the <TD> with class "action1" vs the one with class "action2"? I've considered testing for tap target, but I'd also like to be able to do something more advanced like adding a button or something within a TD as well...

Thoughts? Thanks in advance!

tomalex0
29 Dec 2010, 8:16 PM
http://www.sencha.com/blog/2010/11/11/event-delegation-in-sencha-touch/

ncooley527
30 Dec 2010, 5:16 AM
Thanks for your response, but unfortunately, this doesn't answer my question. I am aware of how to bind/delegate a single templated item to an event, but what I'd like to do is have multiple bindings to various items within the template? Also, what if I wanted to inject an Ext item (ie a button) within the template as well?

ncooley527
30 Dec 2010, 5:22 AM
Or are you referring to the 'fly' method demonstrated here? Please clarify. Thanks so much!


Ext.fly('user-list').on({
tap: myHandler,
delegate: 'img'
});

ncooley527
4 Jan 2011, 12:11 PM
To be clear, fly wouldn't work as it's a templated element... Anyone else have thoughts?

TommyMaintz
14 Jan 2011, 7:04 AM
If you use event delegation, even if you add new items to the list using the template, it will still delegate the taps to your handler. Inside your handler you would check what type of item has been tapped. You could also just bind two different listeners with different delegate properties and different handlers.



Ext.fly('user-list').on({
tap: myHandler1,
delegate: '.action1'
});

Ext.fly('user-list').on({
tap: myHandler2,
delegate: '.action2'
});


or



handler = function(e) {
if (e.getTarget('.action1')) {
}
else if (e.getTarget'.action2')) {
}
}


Does this answer your question?

ncooley527
14 Jan 2011, 8:23 AM
Awesome. Thanks for the response. One more question: a big benefit of DataView's events is that I can get access to the Store associated with the DV with an index. Is that possible using event delegation seeing that the only parameter associated with the delegation is the object e? Would I need to use 'scope: this' for that ? Thanks again for taking the time to respond!

TommyMaintz
14 Jan 2011, 8:40 AM
I think the easiest way to do that is the get the surrounding node of the target, and get the record associated to that node. You can do this like the following



handler = function(e) {
dataview.getRecord(e.getTarget('.x-list-item'));
}