[TIMOB-24435] Windows Module: Receive C++ callback from JS
| GitHub Issue | n/a |
| Type | Improvement |
| Priority | None |
| Status | Closed |
| Resolution | Invalid |
| Resolution Date | 2017-03-22T01:18:11.000+0000 |
| Affected Version/s | Release 6.0.1 |
| Fix Version/s | n/a |
| Components | Windows |
| Labels | n/a |
| Reporter | Ricardo Ramirez |
| Assignee | Kota Iguchi |
| Created | 2017-02-27T22:55:22.000+0000 |
| Updated | 2017-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
JSON Source
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 listeningsomethingfiredevent. In this case you can add listener in JavaScriptYou can fire this callback from the module by executingvar 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); });fireEventlike below.There is another way to do the callback, by callingTITANIUM_FUNCTION(YourModule, doTheMyNumberEvent) { const auto ctx = get_context(); auto e = ctx.CreateObject(); e.SetProperty("my_number", ctx.CreateNumber(12345)); fireEvent("somethingfired", e); }JSObjectas 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); });Example: https://github.com/appcelerator/HAL/blob/master/examples/Widget.cpp#L277TITANIUM_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(); }Thank you Kota !
Closing this for now, this is implemented by HAL framework.