Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

passing callback with fireEvent

So I've been trying out various ways to implement a callback with fireEvent:

function foo(){

function tryCallback(e){

    fn = eval(e.callback);

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(){

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?

— asked March 12th 2010 by Nick Lloyd
  • fireevent
  • fireevent

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?

    — answered March 12th 2010 by Jeff Haynie
    1 Comment
    • Jeff
      When you said, For app events, since they're cross JS context, you can send functions presumably you meant For app events, since they're cross JS context, you *can't* send functions.

      — commented October 6th 2010 by Paul Dowsett
  • 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…

    — answered March 12th 2010 by Nick Lloyd
  • This is a little bit messy but maybe somebody can create much cleaner approach. Anyway code goes like this:


    Ti.App.addEventListener('someEvent', function(e) {
        Ti.API.info("someEvent firing");
        Ti.App.fireEvent('someEvent_cb', {});


    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', {});
    — answered January 4th 2011 by Rey Bumalay
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.