Titanium JIRA Archive
Titanium SDK/CLI (TIMOB)

[TIMOB-24435] Windows Module: Receive C++ callback from JS

GitHub Issuen/a
TypeImprovement
PriorityNone
StatusClosed
ResolutionInvalid
Resolution Date2017-03-22T01:18:11.000+0000
Affected Version/sRelease 6.0.1
Fix Version/sn/a
ComponentsWindows
Labelsn/a
Reporter Ricardo Ramirez
AssigneeKota Iguchi
Created2017-02-27T22:55:22.000+0000
Updated2017-03-22T01:18:11.000+0000

Description

Issue Description

Customer need a way to receive a function (callback) from Javascript in the C++ code by looking at the code in TitaniumKit. Formerly, in Kroll, this would be done by doing something like: (Assuming this is an android module) HashMap args = args; KrollFunction someFunction = (KrollFunction) args.get("someFunction"); [...] someFunction.call(KrollObject, KrollDict); So Would it be possible you provide an example on this if is possible?

Comments

  1. Kota Iguchi 2017-02-28

    Yes it's possible, you can find examples in TitaniumKit because callback pattern has been used a lot in Titanium API. I think easiest way to fire callback is leveraging addEventListener. For instance [Ti.Gesture](https://github.com/appcelerator/titanium_mobile_windows/blob/master/Source/Sensors/src/Gesture.cpp#L28). So let say you are listening somethingfired event. In this case you can add listener in JavaScript
       var YOUR_MODULE = require('YOUR_MODULE'), 
             your_module = new YOUR_MODULE();
       your_module.addEventListener('somethingfired', function(e) {
          Ti.API.info(e.type + ' my_number:' + e.my_number);
       });
       
    You can fire this callback from the module by executing fireEvent like below.
       TITANIUM_FUNCTION(YourModule, doTheMyNumberEvent)
       {
           const auto ctx = get_context();
           auto e = ctx.CreateObject();
           e.SetProperty("my_number", ctx.CreateNumber(12345));
           fireEvent("somethingfired", e);
       }
       
    There is another way to do the callback, by calling JSObject as a function directly. This is basic functionality within [HAL](https://github.com/appcelerator/HAL) framework.
       var YOUR_MODULE = require('YOUR_MODULE'), 
             your_module = new YOUR_MODULE();
       your_module.doTheCallbackImmediately(function(str) {
          Ti.API.info(str);
       });
       
       TITANIUM_FUNCTION(YourModule, doTheCallbackImmediately)
       {
       	ENSURE_OBJECT_AT_INDEX(my_callback, 0);
       
              const std::vector<JSValue> args { get_context().CreateString("TEST") };
       	my_callback(args, get_object());
       	return get_context().CreateUndefined();
       }
       
    Example: https://github.com/appcelerator/HAL/blob/master/examples/Widget.cpp#L277
  2. Ricardo Ramirez 2017-02-28

    Thank you Kota !
  3. Kota Iguchi 2017-03-22

    Closing this for now, this is implemented by HAL framework.

JSON Source