Tabris.js Widgets: Custom iOS Widget

By writing a Custom iOS Widget, we can expose native iOS functionality through a Tabris JavaScript API. Maybe our app needs to access more native platform features than what Tabris provides ‘out of the box.’ We can code our own iOS widget, save JavaScript developers from having to learn Objective-C, and make a heroic open source contribution to the Tabris community.

Our Custom Widget consists of a JavaScript part – the JavaScript API developers will use when building a Tabris App – and a part written in Objective-C that is responsible for leveraging native functionality, hardware, etc. Tabris provides a ‘bridge’ between JavaScript and native code.

In our JavaScript class definition for our Custom Widget, we can pass properties from JavaScript to the native code using:

And invoke native methods using:

Say we are building a custom Map widget. (The full example available as a Cordova plugin is here).

On the JavaScript side in our Custom Widget class we have a method as follows:

We can see that the method calls a native method moveToRegion.

On the native side written in Objective-C, in our Custom Widget class, in our initialization method, we need to ‘register a selector’ to tell the native code how to handle the JavaScript call.

Then we define our selector ‘moveToRegion.’ This function does the actual work of changing the coordinates on our native Map component. The NSDictionary parameter contains the parameters passed on the JavaScript side, namely our region and options properties.

While methods are passed on from the JavaScript to the native code, the native code communicates back to the JavaScript by causing JavaScript events to fire when native events fire.

Finally, our Custom Widget is packaged as a Cordova plugin which can be added to Tabris app projects using cordova plugin add <plugin-id/git-url>.

See the documentation for many more important details.