Titanium - 侦听器回调属于不受支持的类型:__NSDictionary

Titanium - Listener callback is of a non-supported type: __NSDictionary

我在使用 Titanium SDK >= 6.1.0 GA 和 Ti.App.fireEvent iOS 时遇到问题。直到 SDK 6.0.4 GA 使用 Ti.App.fireEvent 和 JSON 字典作为参数工作正常,但从 6.1.0 到最后一个 GA (6.3.0) 我收到以下消息:

Listener callback is of a non-supported type: __NSDictionaryM

我在 KrollBridge.m 中看到了这一行,它可能导致此日志消息:

- (void)fireEvent:(id)listener withObject:(id)obj remove:(BOOL)yn thisObject:(TiProxy*)thisObject_
{
    if (![listener isKindOfClass:[KrollCallback class]])
    {
        NSLog(@"[ERROR] listener callback is of a non-supported type: %@",[listener class]);
        return;
    }

    KrollEvent *event = [[KrollEvent alloc] initWithCallback:listener eventObject:obj thisObject:thisObject_];
    [context enqueue:event];
    [event release];
}

当我在设备上尝试该应用程序时,只有失败,在模拟器上运行正常!

添加一些 NSLog 和 运行 应用程序:

控制台:

Simulator:
[DEBUG] :  Firing app event: event_test
[DEBUG] :  Listener type: KrollCallback
[DEBUG] :  OK

Device:
[DEBUG] :  Firing app event: event_test
[DEBUG] :  Listener type: __NSDictionaryM
[ERROR] :  Listener callback is of a non-supported type: __NSDictionaryM

代码:

Ti.App.addEventListener('event_test', fun);
Ti.App.fireEvent('event_test', data: {"ID": 0, "Value": "Test"});

我不知道为什么。我感觉这是 6.1.0 GA 中引入的一个错误,它会重现,直到最后一个 GA 可用。

有什么建议吗? 谢谢

我想这与此处 Ti.App.fireEvent JIRA 报告的问题相同,标记为 已在 SDK 6.3 中解决。0.GA

务必将您的 Ti SDK 更新到最新的 6.3。0.GA 因为它比其他 6.x 版本更稳定。


推荐的解决方案:

在此处阅读为什么要避免使用 Ti.App.addEventListener 并按照以下步骤设置全局事件侦听器以传递您想要的任何内容。

  1. 在项目的 app -> lib 文件夹中创建一个任意名称的 js 文件,比方说,events_dispatcher.js
  2. 在此文件中添加此代码行:module.exports = _.clone(Backbone.Events);
  3. 现在将您的代码 Ti.App.addEventListener('event_test', fun); 替换为以下代码:

    var eventHandler = require('events_dispatcher');
    
    eventHandler.on('event_test', fun);
    
    
    // to avoid duplication of adding the same event
    // make sure to remove this event when you close the controller
    // or you are planning to re-create the controller 
    
    eventHandler.off('event_test', fun);
    
  4. 最后将此代码 Ti.App.fireEvent('event_test', data: {"ID": 0, "Value": "Test"}); 替换为 - require('events_dispatcher').trigger('event_test', data: {"ID": 0, "Value": "Test"});

这种代码方式看似简单,但却是最值得推荐的方式和最佳解决方案,可以替代Ti.App.fireEvent的所有需求。坚持下去,您将有一个安全的方法来调用任何类型的数据的任何方法。