简体   繁体   中英

How can I use Global variable across multiple functions in JavaScript?

I have a piece of code which is intended to check the permission level and group membership of a use and launch a dialog box if the user has the correct permissions to access that section of the site.

function bindSettingsButton() {
            $("#mt-ngw-personalsettings").on("click", function() {
                RequestNewSite();
            });
        }

        function RequestNewSite()   {
            var HasPermission = false;
            var isGroupMember = false;
            CheckCurrentUserMembership();
            CheckUserHasEditPermissions();
            CheckUserPermissions();
        }

        function CheckCurrentUserMembership() {
            var clientContext = new SP.ClientContext.get_current();
            this.currentUser = clientContext.get_web().get_currentUser();
            clientContext.load(this.currentUser);

            this.userGroups = this.currentUser.get_groups();
            clientContext.load(this.userGroups);
            clientContext.executeQueryAsync(OnQuerySucceeded, OnQueryFailed);
        }

        function OnQuerySucceeded() {
            var isMember = false;
            var groupsEnumerator = userGroups.getEnumerator();
            while (groupsEnumerator.moveNext()) {
                var group = groupsEnumerator.get_current();
                if(group.get_title() == "Create Site OptOut") {
                isMember = true;
                this.isGroupMember = true;
                break;
                }
            }
        }

        function OnQueryFailed() 
        {
            alert("Couldn't check user group membership. Please contact  to resolve this issue.");
        }

        function CheckUserHasEditPermissions()  {
            context = new SP.ClientContext.get_current();
            web = context.get_web();
            this._currentUser = web.get_currentUser();
            this._theList = web.get_lists().getByTitle('siterequests');
            context.load(this._currentUser);
            context.load(this._theList, 'EffectiveBasePermissions')
            context.executeQueryAsync(Function.createDelegate(this, this.onPermissionsSuccessMethod), Function.createDelegate(this, this.onPermissionsFailureMethod));
        }

        function onPermissionsSuccessMethod(sender, args)   {
            if (this._theList.get_effectiveBasePermissions().has(SP.PermissionKind.editListItems))
            {
                this.HasPermission = true;
            }
            else
            {
                this.HasPermission = false;
            }
        }

        function onPermissionsFailureMethod()
            {
                alert("Couldn't check permissions. Please contact  to resolve this issue.");
            }

        function CheckUserPermissions() {
            if(this.isGroupMember == true)
            {
                alert("You do not have permission to create sites. If you believe you should have access to this functionality, please contact .");
            }
            else if(this.HasPermission == false)
            {
                alert("You do not have permission to create sites. If you believe you should have access to this functionality, please contact .");
            }
            else
            {
                showDialogue();
                document.getElementById("next-stage").focus();
            }
        }

Unfortunately when it reaches the end this section the variables HasPermission and isGroupMember are still undefined so the dialogue launches automatically for every user. I have a feeling I have misused the .this keywords and this is a scoping error but I am not expert enough in JS to know for certain or be able to fix it. Can anyone tell me exactly what I've done wrong and how to fix it please?

 $("#mt-ngw-personalsettings").on("click", function() { RequestNewSite(); }); 

If you are expecting to use RequestNewSite as a constructor, you need to use new to allocate it. If you call as a function no object (and thus state) is created.

Additionally all members of the type need to be created explicitly on this .

So

 function RequestNewSite() { var HasPermission = false; var isGroupMember = false; CheckCurrentUserMembership(); CheckUserHasEditPermissions(); [...] 

Needs to be

function RequestNewSite()   {
  this.HasPermission = false;
  this.isGroupMember = false;
  this.CheckCurrentUserMembership();
  this.CheckUserHasEditPermissions();
  [...]

You are performing async functions, which means the rest of the code will keep executing even though the stuff you have started first are not completed yet. You will have to call the CheckUserPermissions after onPermissionsSuccessMethod and the OnQuerySucceeded function has completed.

In addition to this the HasPermission and isGroupMember variables are local to the RequestNewSite function, which means they are out of the scope of the CheckUserPermissions function.

    var HasPermission = false;
    var isGroupMember = false;
    var CompletedCallbacks = 0;
    function bindSettingsButton() {
        $("#mt-ngw-personalsettings").on("click", function() {
            RequestNewSite();
        });
    }

    function RequestNewSite()   {
        CheckCurrentUserMembership();
        CheckUserHasEditPermissions();
    }

    function CheckCurrentUserMembership() {
        var clientContext = new SP.ClientContext.get_current();
        this.currentUser = clientContext.get_web().get_currentUser();
        clientContext.load(this.currentUser);

        this.userGroups = this.currentUser.get_groups();
        clientContext.load(this.userGroups);
        clientContext.executeQueryAsync(OnQuerySucceeded, OnQueryFailed);
    }

    function OnQuerySucceeded() {
        var isMember = false;
        var groupsEnumerator = userGroups.getEnumerator();
        while (groupsEnumerator.moveNext()) {
            var group = groupsEnumerator.get_current();
            if(group.get_title() == "Create Site OptOut") {
            isMember = true;
            isGroupMember = true;
            break;
            }
        }
        CompletedCallbacks++;
        CheckUserPermissions();
    }

    function OnQueryFailed() 
    {
        alert("Couldn't check user group membership. Please contact SPCOE@capita.co.uk to resolve this issue.");
    }

    function CheckUserHasEditPermissions()  {
        context = new SP.ClientContext.get_current();
        web = context.get_web();
        this._currentUser = web.get_currentUser();
        this._theList = web.get_lists().getByTitle('siterequests');
        context.load(this._currentUser);
        context.load(this._theList, 'EffectiveBasePermissions')
        context.executeQueryAsync(Function.createDelegate(this, this.onPermissionsSuccessMethod), Function.createDelegate(this, this.onPermissionsFailureMethod));
    }

    function onPermissionsSuccessMethod(sender, args)   {
        if (this._theList.get_effectiveBasePermissions().has(SP.PermissionKind.editListItems))
        {
            HasPermission = true;
        }
        else
        {
            HasPermission = false;
        }
        CompletedCallbacks++;
        CheckUserPermissions();
    }

    function onPermissionsFailureMethod()
        {
            alert("Couldn't check permissions. Please contact SPCOE@capita.co.uk to resolve this issue.");
        }

    function CheckUserPermissions() {
        if(CompletedCallbacks != 2) return;
        if(isGroupMember == true)
        {
            alert("You do not have permission to create sites. If you believe you should have access to this functionality, please contact SPOCOE@capita.co.uk.");
        }
        else if(HasPermission == false)
        {
            alert("You do not have permission to create sites. If you believe you should have access to this functionality, please contact SPOCOE@capita.co.uk.");
        }
        else
        {
            showDialogue();
            document.getElementById("next-stage").focus();
        }
    }

This code should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM