IT:AD:Sencha Touch:HowTo:Setup Event Handlers in Views
Summary
Process
As per lifespan, use the View's initialize event to add items:
//NB: use 'get' (not [pos]) as 'items' is a 'MixedCollection'.
//Scope set via second argument:
this.items.get(5).on('tap', this.buttonHandler, this);
Example:
Ext.define("Spike01.view.Splash", {
extend: 'Ext.Panel',
xtype: 'splash',
constructor: function(config) {
// Use of Constructor knocks out controller ref,
// due to id changing.
this.callParent(config);
},
initialize: function(){
this.callParent(arguments);
//Add buttons 2,3,4 (processed after 'config' items)
this.add([
{
xtype: "button", text: 'Button #4',
//Handler's context will be btn
handler: this.buttonHandler,
},
{
xtype: "button", text: 'Button #5',
//Handler's context will be this view (not btn)
handler: this.buttonHandler, scope: this
},
{
//Handler's context will be this view (not btn)
//due to event handler attached below:
xtype: "button", text: 'Button #6',
},
{
//Link to registered controller route:
xtype:"panel",html:"<a href='#main/goCrazy'>!</a>"
},
{
//Link to registered route:
xtype:"panel",html:"<a href='#goCrazy'>***</a>"
}
]);
//NB: use 'get' (not [pos]) as 'items' is a 'MixedCollection'.
//Scope set via second argument:
this.items.get(5).on('tap', this.buttonHandler, this);
},
config: {
styleHtmlContent: true,
layout: 'vbox', align:'center', pack:'center',
items : [
{
xtype: 'button', text: 'Button #1',
listeners: {
tap: {
fn: function() {
alert('fired. Context:' + this.id);
this.fireEvent("GoCrazy",this);
},
//no scope defined. Context = button#1
}
}
},
{
xtype: 'button', text: 'Button #2',
listeners: {
tap: {
//Bug? Scope should be this view,
//but Context=windows
//,so avoid: scope:this,
fn: function() {
alert('fired. Context:' + this);
this.fireEvent("GoCrazy",this);
}
}
}
},
{
xtype: 'button', text: 'Button #3',
listeners: {
//incorrect: tap: this.buttonHandler
//Will fail (this being nothing, as context is unset)
tap: function() {this.buttonHandler();}
}
}
]
},
buttonHandler:function() {
alert('fired! Context:' + this);
//If the context is the button:
this.parent.fireEvent("GoCrazy",this);
//if the context is the view:
this.fireEvent("GoCrazy",this);
}
});