Search code examples
widgetappceleratorappcelerator-alloy

How to require a widget/lib in app/controller?


Is it possible to access a library file under a widget/lib folder from an appController?

I tried

require('./widgets/com.myWidget/lib/myLib')

and

require('widgets/com.myWidget/lib/myLib')

All these throw error:

[ERROR] :  Script Error Couldn't find module: ./widgets/com.myWidget/lib/myLib for architecture: i386

How do I require com.myWidget/lib/myLib.js in controllers/myCtrlr.js?

Or should all lib code live only under app/lib?

app
|--assets
|--controllers
    |--myCtrlr.js
|--lib
|--models
|--styles
|--views
|--widgets
   |--com.myWidget
       |--assets
       |--controllers
       |--lib
           |--myLib.js
       |--models
       |--styles
       |--views

Solution

  • You can't access directly widget lib from your app. When you create an instance of your widget with Widget.createWidget(widget_name, [controller_name], [params]) it load the widget.js controller.

    I think the best way to access your lib is to add it in app/lib Because from your widget you can access your lib with require(mylib)

    If you really want access your lib from your widget, you can create a function to export it like this :

    In widget.js :

    $.loadLib = function(){
     return require(WPATH(myLib));
    };
    

    In index.js :

    var w = Widget.createWidget('com.myWidget');
    var myLib = w.loadLib(); //contains myLib located in com.myWidget/lib/