Farhad-Taran
Farhad-Taran

Reputation: 6512

require js defining modules in html script tags

I am trying to define a module for the initual configuration options of my app inside an script tag in my html. but I get the following error:

Error: Module name "options" has not been loaded yet for context: _. Use require([]) http://requirejs.org/docs/errors.html#notloaded

here is the html:

<script src="Scripts/require.js" data-main="/Recruiter/temp-search/App/main"></script>
<script> 

    define('options',['jquery'],function($) {        
        return options = {
            salesPhoneNumber : '@ConfigurationManager.AppSettings.Get("SalesPhoneNumber")',
            saleInfoMessage : "To access Temp Search candidate details, please call our team on " + salesPhoneNumber,
            subscriptionInfo : @Html.Raw(new JavaScriptSerializer().Serialize(Model.AccessInfo ?? null)),
            questionProLink: src="@(Request.Url.Scheme)://www.questionpro.com/a/TakeSurvey?id=@(Model.IsRecCon ? AppSettings.SurveyRecConId : AppSettings.SurveyOthersId)&amp;[email protected]&amp;[email protected]",
            surveyEnabled: '@AppSettings.FlexSurveyEnabled',
            whatsNewUrl: '@AppSettings.UrlWhatsNew',
            salesPhoneNumber:salesPhoneNumber,
            showSaleInfo: '@ViewBag.ShowSaleInfo',
            fileDownloadFailCookieName:'@AppSettings.FileDownloadFail',
            urls: {
                signInUrl: '@string.Format("https://{0}/recruiter/account/signIn", Url.RequestContext.HttpContext.Request.Url.Host)',
                signInTempsHome: '/recruiter/temp-search/home',
                signInTempsSearch: '/recruiter/temp-search/api/temps',
                checkAvailabilityUrl: '/recruiter/temp-search/api/availability',
                searchUrl: '/recruiter/temp-search/api/temps/search',
                accesslimitUrl: '/recruiter/temp-search/api/ecruiters/accessinfo',
                previewUrl: '/recruiter/temp-search/api/temps/preview'
            },
            elements: {
                signInRegisterDialog: $("#signInRegisterDialog"),
                noSubscriptionDialog: $("#noSubscriptionDialog"),
                searchForm: $("#searchForm"),
                searchKeywords: $("#Keywords"),
                searchLocation: $("#Location"),
                searchRadius: $("#Radius"),
                searchSortBy: $("#sortBy"),
                searchTemp: $("#Temporary"),
                searchContract: $("#Contract"),
                searchPayRateFrom: $("#PayRateFrom"),
                searchPayRateTo: $("#PayRateTo"),
                searchAvailability: $("#AvailabilityConfirmed"),
                locationErrorMsg: $("#locationErrorMsg"),
                checkAll: $(".checkAll"),
                checkCandidate: $(".checkCandidate"),
                availability: {
                    availabilityBtn: $("#availabilityBtn"),
                    availabilityDialog: $("#availabilityDialog"),
                    additionalInformation: $("#AdditionalInformation"),
                    jobPosition: $("#JobPosition"),
                    jobLocation: $("#JobLocation"),
                    payRate: $("#JobPayRateFrom"),
                    payRateTo: $("#JobPayRateTo"),
                    startOn: $("#StartOnDate"),
                    duration: $("#Duration"),
                    checkAvailabilityForm: $("#checkAvailabilityForm"),
                    availabilityLocation: $("#checkAvailabilityForm #JobLocation"),
                    candidateIds: $("#CandidateIds"),
                    tempJobId: $("#TempJobId"),
                    msgPanel: $("#msgPanel"),
                    msg: $(".msg"),
                    errorAvailability: $("#availabilityError"),
                    availabilityConfirmationDialog: $("#availabilityConfirmationDialog"),
                    infoBubbleMessage : $("#infoBubbleMessage"),
                    availabilityConfirmationMsg: $("#availabilityConfirmationDialog .msgDialog"),
                    downloadInfoLink : $("#downloadInfoLink")
                },
                preview: {
                    previewBtn: $('.previewBtn')

                },
                messagePanel: $("#messagePanel")
            },
            minWageRate : @Constants.Range.ApprenticeshipsPerHourMin,
            authentication : @(Request.IsAuthenticated.ToString().ToLower()),
            minDate: '@String.Format("{0:yyyy/MM/dd}", DateTime.Now)',
            pageInfo: {
                number: @Model.Results.PageNumber,
                size: @Model.Results.PageSize,
                resultsCount: @Model.TotalResultsCount
            },
            criteria : @Html.Raw(new JavaScriptSerializer().Serialize(Model.Criteria)),
            remainingAccessLimit: @Model.AccessInfo.Remaining,
            totalAccessLimit: @Model.AccessInfo.Limit,
            availableCandidates: @Model.AvailableCandidates,
            candidates: @Html.Raw(new JavaScriptSerializer().Serialize(Model.Results ?? Model.Results.ToJSON()))
        };
    })
</script>

Upvotes: 2

Views: 7230

Answers (1)

Louis
Louis

Reputation: 151441

The problem is not with the code you show in your question but with how you ask RequireJS to load your module. The error message you show happens when you do a require call of this form:

var foo = require('foo');

This kind of require call does not work unless foo is already loaded, and to ensure it is already loaded you can manually load it yourself, or you can have RequireJS do it for you. However, to get RequireJS to do it for you, you need to write your code in a certain way. If you want a module to use foo and you want to use the require above then, you should do:

define(function (require) {
    var foo = require('foo');
    ...
});

Or if you need to use module and exports, the callback can be function (require, exports, module) {....

Also, you should perform the following operations in this order:

  1. Load RequireJS.

  2. Execute define('options', ....

  3. Then and only then start loading your application.

This means removing data-main and using an explicit require call after define('options'.

Upvotes: 3

Related Questions