Reputation:
Say we have a form with a lot of elements.
I'd like a way through generic code, to be able to add listeners to these elements so that for example, all the elements with a built-in focus
event, like text inputs or dropdowns, will have this onFocus
listener. In rough pseudo-code, something like this:
for each element in document
if hasBuiltInFocusEvent(element)
element.addListener(element, 'focus', indicateOnFocus);
function indicateOnFocus(element)
{
log(currentTime(), element.id, 'focus');
}
Ideally, without having to modify the existing class definitions of the elements. I can just have the code called once before the form is displayed to set up the listeners.
Please excuse my general lack of knowledge. I'm interested in whether this is feasible, in particular avoiding having to hardcode a listener for every element, because a common generic method has numerous advantages.
Upvotes: 1
Views: 1153
Reputation: 3150
There are several ways to accomplish this. For the focus event, as DrakeES mentioned, it's already there.
For events that are not you can for example bubble events from the fields (like in a base field class) up to the form. In the form you can listen to that event and in the handler you can look at which field did bubble the event up.
Here is some non tested code:
Ext.create('Ext.form.Panel', {
fullscreen: true,
items: [
{
xtype: 'fieldset',
title: 'Enter your name',
items: [
{
xtype: 'textfield',
**bubbleEvents: 'TheEvent',**
label: 'First Name',
name: 'firstName'
},
{
xtype: 'textfield',
**bubbleEvents: 'TheEvent',**
label: 'Last Name',
name: 'lastName'
}
]
}
],
listeners: {
/*
* TheEvent( this, e, eOpts )
*
* this : Ext.field.Field
* e : Event - The tap event
* eOpts : Object - The options object passed to Ext.util.Observable.addListener.
*/
TheEvent: function (field, event, opt) {
/*
* fireEvent( eventName, args ) : Boolean
*
* eventName : String - The name of the event to fire.
* args : Object... - Variable number of parameters are passed to handlers.
*/
this.fireEvent('formfieldTheEvent', field, event, opt);
}
}
});
From there you can listen to 'formfieldTheEvent' from within your controller or whatever and check which field fired the event, for example by name or id or action.
You can also accomplish this by binding events in eventdomains. With the correct selector you can select all fields on a form and bind the event you like.
Ext.define('CustomController', {
extend: 'Ext.app.Controller',
init: function() {
this.listen({
controller: {},
component: {
'textfield': {
TheEvent: function(field, event, eOpts ) {
....
}
}
},
direct: {},
global: {},
store: {}
});
}
})
Upvotes: 0
Reputation: 3734
Focus changes are reported globally in Ext JS out of the box:
Ext.on('focus', function(data) {
console.log('Focus changed from ' + data.fromElement + ' to ' + data.toElement);
});
Upvotes: 2