passing callback with fireEvent
So I've been trying out various ways to implement a callback with fireEvent:
function foo(){
alert('foo');
}
function tryCallback(e){
fn = eval(e.callback);
fn.call(e);
};
Ti.App.addEventListener('tryCallback', tryCallback);
and then from any context I can call:
Ti.App.fireEvent('tryCallback', {callback:'foo'});
this works great.
What I'd love to be able to do, but haven't been able to pull off is to provide an inline callback to be eval'd ie:
Ti.App.fireEvent('tryCallback', {callback: function(){
alert('bar');
}
});
in the hope that I can reference objects in the current context.
Unfortunately, I get App Error: attempt to insert nil object.
Any thoughts on how I might be able to pull this off, or if I'll still be able to reference 'non-global' objects if I do?
3 Answers
-
Yeah, this is probably not obvious. I'll update the doc to reflect this.
For app events, since they're cross JS context, you can send functions. You can only send JSON serializable data.
are you simply trying to pass functions as a convenience?
-
Yea I guess I'm just trying to clean up some of the mess I'm making…
I have a couple functions that are called from different places within my app that I'd like to be able to call, and act on the returned data in the relative context…
This make sense? I may have just confused myself :-s
I've been able to do this by adding additional app.eventListeners in the 'local' contexts, but I'm not sure this is the right approach…
-
This is a little bit messy but maybe somebody can create much cleaner approach. Anyway code goes like this:
app.js
Ti.App.addEventListener('someEvent', function(e) { Ti.API.info("someEvent firing"); Ti.App.fireEvent('someEvent_cb', {}); });
anotherWindow.js
Ti.App.addEventListener('someEvent_cb', function(e) { Ti.API.info("callback received..."); // make sure to remove listener after it has been executed Ti.App.removeEventListener('someEvent_cb', {}); }); Ti.App.fireEvent('someEvent', {});