titaniumtitanium-modulestitanium-proxy

Call JavaScript function from native in Titanium


How to call a JavaScript function from native Android module in Titanium. I want to register a JavaScript function in application view to listen for some events in native module and call back that function from native when that event happens.


Solution

  • The ModDevGuide by Appcelerator is a great place to learn how to do things like this. It's available here for both iOS and Android:

    https://github.com/appcelerator/titanium_modules/tree/master/moddevguide/mobile

    The "KrollDemoProxy" is what you want to look closer at.

    On Android, the native side is here: https://github.com/appcelerator/titanium_modules/blob/master/moddevguide/mobile/android/src/ti/moddevguide/KrollDemoProxy.java

    On iOS, the native side is here: https://github.com/appcelerator/titanium_modules/blob/master/moddevguide/mobile/ios/Classes/TiModdevguideKrollDemoProxy.m

    And this is consumed by JavaScript like this, for both platforms: https://github.com/appcelerator/titanium_modules/blob/master/moddevguide/mobile/android/example/demos/krollCallbacksAndEventsDemo.js

    Search for the word "success" in those files, and you'll be able to figure out how it's firing that "success" event back to JavaScript-land.

    Hope this helps.