tomaytotomato
tomaytotomato

Reputation: 4028

Cannot access functions inside Javascript function wrapper?

All,

My code was failing JSLint for the "use strict" issue. As suggested here : Disable "use the function form of use strict" but keep the "Missing 'use strict' statement" warning

If you wrap all the functions in the javascript file with another function wrapper, it will solve this issue.

However now after doing this all my functions are undefined when I call them from the page?

(function () {
"use strict";

/**
 * Update the page with a message informing the user
 * an email has been sent to their email address
 * @param details user details (email address)
 */
function shareEmailSent(details) {

    // unhide confirmation message
    $('strong#emailAddress').text(details.email);
    $('#confirmationMessage').removeClass('hide');
}

/**
 * Handle error
 */
function showError() {
    return false;
}

/**
 * Makes a POST request to send the current user
 * an email containing their unqiue share url
 * @param emailList
 */
function sendEmail(emailList) {
    var data = {};
    data.formToken = $('#formToken').val();
    data.emails = emailList;
    $.mooAjax({
        url: "/ajax/share/refer_a_friend_email.php",
        type: "POST",
        data: data,
        dataType: "json",
        error: showError,
        success: function (response) {
            shareEmailSent(response);
        }
    });
}
}());

e.g.

shareEmailSent is not defined

How can I fix this but also pass the JSLint issue as well?

Thanks

Upvotes: 0

Views: 196

Answers (1)

Quentin
Quentin

Reputation: 943599

There are several approaches you can take. In descending order of niceness:

  1. Don't call the functions from outside. Bind all your event handlers using JavaScript (e.g. with addEventListener)
  2. Use the revealing module pattern
  3. Explicitly make functions globals (e.g. with window.someFunction = someFunction).

Obviously, since sendEmail calls the other functions itself, it is probably the only one that would need to be exposed if you used the second or third approach.

Upvotes: 1

Related Questions