0

Not sure what I'm doing wrong here because this code is working in other places I've used it but... in SharePoint, there's a client-side control that can sometimes take a little bit of time to render and get going before we can do stuff with it. So I've come up with a little trick to basically check and see if the appropriate libraries have loaded and are ready for use before I try to do things. It's super simple stuff:

function createSPPeoplePicker(field){
    var onPickerInit = function() {
        if(SPClientPeoplePicker && SPClientPeoplePicker.SPClientPeoplePickerDict){
            var spPP = SPClientPeoplePicker.SPClientPeoplePickerDict[field];
            //Now do stuff with the field.
        } else {
            setTimeout(function() { 
                onPickerInit();
            }, 100);
        }
    }
    onPickerInit();
}

So, basically, if the objects SPClientPeoplePicker and SPClientPeoplePicker.SPClientPeoplePickerDict exist, then do stuff. Otherwise, wait a tick, then check again.

This has been working more or less flawlessly on so many other apps I've built in our environment but now this one. I can't help but think I'm making a JavaScript error, not a SharePoint one, as I'm getting an Uncaught Reference Error yelling at me that SPClientPeoplePicker is not defined when I'm checking if it's defined or not. Is undefined not read as "false" anymore? Am I missing something else stupid?

Appreciate your time, folks, and your patience for dealing with an aggressively bad dev.

ChrisPEditor
  • 197
  • 11
  • 1
    is your `SPClientPeoplePicker` variable declared somewhere ? – Nicolas Feb 04 '20 at 16:02
  • 2
    `SPClientPeoplePicker` is **not** defined, not `undefined`. Two different concepts. If it's not defined, it's *not even declared*, so you're trying to read a binding that doesn't exist. This causes an error. If it's `undefined`, then it's *declared* but no value has been assigned (yet). – VLAZ Feb 04 '20 at 16:02
  • 1
    Does this answer your question? [variable === undefined vs. typeof variable === "undefined"](https://stackoverflow.com/questions/4725603/variable-undefined-vs-typeof-variable-undefined) – VLAZ Feb 04 '20 at 16:03

1 Answers1

0

Answering my own question. I guess, at the point at which I'm calling this, the variables aren't even declared (thanks to the comments on the question for pointing me in the right direction).

Changed to:

function createSPPeoplePicker(field){
    var onPickerInit = function() {
        if(typeof SPClientPeoplePicker !== "undefined" && SPClientPeoplePicker.SPClientPeoplePickerDict !== "undefined"){
            var spPP = SPClientPeoplePicker.SPClientPeoplePickerDict[field];
            //Now do stuff with the field.
        } else {
            setTimeout(function() { 
                onPickerInit();
            }, 100);
        }
    }
    onPickerInit();
}

And now we're good to go. Thanks, folks.

ChrisPEditor
  • 197
  • 11