Search code examples
javascriptjqueryrequirejssapui5

How to require a requirejs module using jquery?


Lets say i have this ResourceBundleContext.js file (requirejs module):

sap.ui.define([
   "sap/ui/model/resource/ResourceModel"
], function (ResourceModel)
{
    'use strict';
    var resourceBundleContext = function ()
    {
        var i18nModel = new ResourceModel({
            bundleName: "sap/rules/ui/src/sap/rules/ui/lib/parser/i18n.messages_descriptions"
        });
        return {
            getString: function (messageKey, paramsArray)
            {
                var oBundle = i18nModel.getResourceBundle();
                var sMsg = oBundle.getText(messageKey, paramsArray);
                jQuery.sap.log.debug("code: " + messageKey + ", params: " + paramsArray + "\nMessage: " + sMsg);
                return sMsg;
            }
        };
    };
    return new resourceBundleContext;
});

in the path:

sap.hrf.ui.uilib.js.parser.infrastructure.locale.lib.resourceBundleContext

And i want to require this above module using jquery, this will bot be good:

jQuery.sap.require("sap.hrf.ui.uilib.js.parser.infrastructure.locale.lib.resourceBundleContext");

How i can require a requirejs module using jQuery?

Thanks!


Solution

  • Thats because you are mixing the 'old' synchronous requirejs and the new asynchronous AMD modules. You have two possible solutions:

    1. In your module definition you have to give sap.ui.define() true as last parameter to export the module into the global namespace so that you can access it after a jquery.sap.require().
    sap.ui.define([
       "sap/ui/model/resource/ResourceModel"
    ], function (ResourceModel)
    {
        'use strict';
        var resourceBundleContext = function ()
        {
            var i18nModel = new ResourceModel({
                bundleName: "sap/rules/ui/src/sap/rules/ui/lib/parser/i18n.messages_descriptions"
            });
            return {
                getString: function (messageKey, paramsArray)
                {
                    var oBundle = i18nModel.getResourceBundle();
                    var sMsg = oBundle.getText(messageKey, paramsArray);
                    jQuery.sap.log.debug("code: " + messageKey + ", params: " + paramsArray + "\nMessage: " + sMsg);
                    return sMsg;
                }
            };
        };
        return new resourceBundleContext;
    }, true /* export to global namespace */); //<-- there's the true
    
    1. You have to use sap.ui.require() to load your AMD module the AMD way:
    sap.ui.require("sap/hrf/ui/uilib/js/parser/infrastructure/locale/lib/resourceBundleContext",
                   function(resourceBundleContext){
                     // called asynchronously when the module has loaded.
                     // resourceBundleContext is your module
                   });