I'm having a problem with my javascript code that I am sure is to do with scope, but I can't figure out where I'm going wrong.
I'm trying to write a method that will allow me to retrieve items in a list. I've followed numerous examples online, but as I said, I think it is a scope issue.
My Code is below
It includes an spHelper IIFE (immediately invoked function expression - or self executing anonymous function) that sets up my context and has the success/failure functions.
Outside the IIFE, I make the function call.
/*
IIFE code for retrieving sp lists
*/
var spHelper = (function ($, SP, rootSP) {
var clientContext = new SP.ClientContext(rootSP);
var publicfunctions = {};
var itemCollection = {};
var onSPQueryFailure = function(sender, args) {
alert("Request failed. " + args.get_message() + "\n" + args.get_stackTrace());
}
var onListRetrieveSuccess = function(sender, args) {
var html = "";
var listItemEnumerator = itemCollection.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
html += "<li>" + oListItem.get_item("Title") + "</li>";
}
$("#AdditionalFilters").append("<ul>" + html + "</ul>");
}
publicfunctions.createRefiners = function (listName, include) {
itemCollection = clientContext.get_web().get_lists().getByTitle(listName).getItems('');
clientContext.loadQuery(itemCollection, include);
clientContext.executeQueryAsync(onListRetrieveSuccess, onSPQueryFailure);
}
return publicfunctions;
}(jQuery, SP, "/sites/SDA"));
spHelper.createRefiners("Ref_Process_Group","Include(Id,Title)");
The code seems to execute until the var listItemEnumerator = itemCollection.getEnumerator()
line. At that point I get an error:
The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
Because the query seems to be executing and loading the 'Success' method, I am sure it is some kind of scope issue in JavaScript but I have been going round in circles and can't work it out.
{}
When I get to theclientContext.loadQuery(itemCollection)
the itemCollection is initialised with some SharePoint fields (which are minimized so they have unfathomable names:$0_0
and$4_0
) Later, in the successHandler, the itemCollection is still initialized with the SharePoint properties. I can't really step into it because it goes into the minimized SP.js files from SharePoint