mardi 4 février 2020

JavaScript if/else statement not evaluating undefined variable

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.

Aucun commentaire:

Enregistrer un commentaire