PDA

View Full Version : Triggering arbitrary events?



schvenk
28 Nov 2010, 10:43 AM
I'm setting up an app using (roughly) MVC, which means I need my view (or objects within it) to generate arbitrary events that my controller can then listen for.

in jQuery I can have any object fire arbitrary events and then listen for them, e.g.:


var myObject = (function() {
this.doSomething = function() {
$(this).trigger('testEvent');
};
})();

$(myObject).bind('testEvent', function() { alert('Test event fired.'); });


In that example, calling myObject.doSomething() would result in the alert "Test event fired" being shown.

What's the Sencha Touch equivalent for this?

Thanks!

evant
28 Nov 2010, 1:37 PM
MyClass = Ext.extend(Ext.util.Observable, {

constructor: function(){
this.addEvents(
'event1',
'event2'
);
MyClass.superclass.constructor.apply(this, arguments);
},

someMethod: function(x){
if (x == 1) {
this.fireEvent('event1', this, 'the value is 1');
} else {
this.fireEvent('event2', this, 'the value is 2');
}
}
});

var o = new MyClass();
o.on('event1', function(){
console.log(arguments);
})
o.someMethod();

schvenk
28 Nov 2010, 6:06 PM
Thanks. So is Ext.extend() sort of the creation-time equivalent of jQuery's run-time $() call? Makes your object addressable by Sencha?

Also, what's the purpose of the addEvents() method? Seems like I can call fireEvent() with an arbitrary string as event name without calling addEvents() first...

evant
28 Nov 2010, 6:07 PM
No, extend creates a new class.