Batman
Batman

Reputation: 6353

Simplifying if statement

I have a function with an if statement which contains two separate AJAX call operations. Based on a variable called subjectType, the conditions for the call change. If I'm trying to get user information I need to give it the userLoginName. If I'm trying to get Site information I need to give it the webURL.

I can accomplish this using an if statement but is there a better way to do this without having to repeat most of the lines?

var subjectType = if(/*I'll check the value of the drop down to see if a user or site report was asked for*/)?"GetGroupCollectionFromUser":"GetGroupCollectionFromWeb";

function parseSubjectColFromUser(subject){
  var subjectGroups = [];
  if (subjectType){
    $().SPServices({
      operation: "GetGroupCollectionFromUser",
      userLoginName: subject,
      completefunc: function(xData, Status){
        $(xData.responseXML).find("Group").each(function(){
            subjectGroups.push($(this).attr('Name'));
        });
      }
    });
  }else{
    $().SPServices({
      operation: "GetGroupCollectionFromWeb",
      webURL: subject,
      completefunc: function(xData, Status){
        $(xData.responseXML).find("Group").each(function(){
            subjectGroups.push($(this).attr('Name'));
        });
      }
    });
  }
  return subjectGroups;
}

Upvotes: 0

Views: 304

Answers (1)

Cameron Askew
Cameron Askew

Reputation: 1413

Should be pretty easy...I also assumed you wanted to use a callback function here since you're doing this via an AJAX request.

function parseSubjectColFromUser(subject, myCallback){
    var subjectGroups = [];
    var params = {
        operation: subjectType ? "GetGroupCollectionFromUser" : "GetGroupCollectionFromWeb",
        completefunc: function(xData, Status){
            $(xData.responseXML).find("Group").each(function(){
                subjectGroups.push($(this).attr('Name'));
            });
            myCallback(subjectGroups);
        }
    };

    if (subjectType) {
        params.userLoginName = subject;
    } else {
        params.webURL = subject;
    }

    $().SPServices(params);
}

Upvotes: 3

Related Questions