Skip to content

Instantly share code, notes, and snippets.

@jackslocum
Created September 10, 2014 21:22
Show Gist options
  • Save jackslocum/7ff2b8db16f848004b44 to your computer and use it in GitHub Desktop.
Save jackslocum/7ff2b8db16f848004b44 to your computer and use it in GitHub Desktop.
Better Declarative Listeners for ExtJS
/**
* @author Jack Slocum
* MIT License
*
* Adds support for "listens" config on components.
* http://jackslocum.com/blog/listens/
*/
Ext.define('xui.mods.Listens', {
override: 'Ext.Component',
afterRender: function(){
var ls = this.listens;
if(typeof ls === 'object'){
var qcache = {};
for(var k in ls){
if(ls.hasOwnProperty(k)){
var sels = k.split(/\s*,\s*/g),
fn = ls[k];
if(typeof fn === 'string'){
fn = this[fn];
}
for(var i = 0, len = sels.length; i < len; i++){
var ks = sels[i].split('@'),
query = ks[0],
c = qcache[query];
if(!c){
if(query === 'this'){
c = this;
} else {
var char = query.charAt(0);
if(char === '$'){
c = Ext.getStore(query.substr(1));
} else if(char === '^'){
c = this.up(query.substr(1));
} else {
c = this.down(query);
}
}
}
if(!c){
throw new Error('Unable to attach listens event. Component not found: ' + query);
} else {
qcache[query] = c;
}
this.mon(c, ks[1], fn, this);
}
}
}
}
this.callOverridden();
},
onClassExtended: function(cls, data){
var sc = cls.superclass,
ls = data.listens;
if(ls && sc.listens && data.inheritListens !== false){
data.listens = Ext.apply({}, ls, sc.listens);
}
}
});
@mijzcx
Copy link

mijzcx commented Apr 4, 2015

Hi, I have some few corrections to suggest especially using this in sencha touch 2

  1. use: chr instead of char variable - this produce error in sencha build (reserve word collision)
  2. use: initialize() instead afterRender() override - as deprecated
  3. use: c.on(ks[1], fn, this) instead of this.mon(c, ks[1], fn, this) - as deprecated

Thank you very much for sharing this code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment