powered by simpleCommunicator - 2.0.48     © 2025 Programmizd 02
Форумы / HTML, JavaScript, VBScript, CSS [игнор отключен] [закрыт для гостей] / Undefined
7 сообщений из 7, страница 1 из 1
Undefined
    #40085789
Фотография Relic Hunter
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Есть шарепоинт в локалке. Много JS кастомного кода. Особых проблем нету. Начальство приказало закинуть шарик в тучу. Закинули. И есть там код.
Код: javascript
1.
2.
3.
4.
5.
	        // Render and initialize the picker. 
        	// Pass the ID of the DOM element that contains the picker, an array of initial
	        // PickerEntity objects to set the picker value, and a schema that defines
        	// picker properties.
	        SPClientPeoplePicker_InitStandaloneControlWrapper(eleId, null, schema);


Он срабатывает 100% в локалке и 50%/50% в туче, т.е. не находит ее undefined. Эта функция глобальная и определена где-то в скриптах шарика. Как быть, где рыть?
...
Рейтинг: 0 / 0
Undefined
    #40085879
ShSerge
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Перекинуть вопрос в дотнет?
...
Рейтинг: 0 / 0
Undefined
    #40085881
alectr
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Видимо скрипты загружаются программно, а-ля:

Код: javascript
1.
2.
3.
4.
5.
6.
const script1 = document.createElement('script');
const script2 = document.createElement('script');
script1.src = 'pathToFile1';
script2.src = 'pathToFile2';
document.head.appendChild(script1);
document.head.appendChild(script2);



Возможно метод лежит в скрипте который аппендится к DOM самым первым, например в script1 как в примере выше.
А в script2 идет обращение к этому методу.
Но такой порядок,
Код: javascript
1.
2.
document.head.appendChild(script1);
document.head.appendChild(script2);


не гарантирует что script1 загрузится первым с сервера.
Локально порядок может быть всегда гарантирован, так как никакой асинхронщины в общении с сервером нет.
Поэтому иногда ваш файл с методом загружается позже чем другой файл в котором идет обращение к этому методу.

Скорее всего как то так. В общем нужно разбираться как организован порядок загрузки скриптов.
...
Рейтинг: 0 / 0
Undefined
    #40086523
Фотография Relic Hunter
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
alectr,

И там и там clientforms.js скрипт грузится где определена эта глобальная функция.

Вот таким моим кодом она подгружается.


Код: javascript
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
$(document).ready(function () {

    RegisterScriptFiles('clienttemplates.js');
    RegisterScriptFiles('clientforms.js');
    RegisterScriptFiles('clientpeoplepicker.js');
    RegisterScriptFiles('autofill.js');

    function RegisterScriptFiles(filename) {
        var scriptEle = document.createElement('script');
        scriptEle.setAttribute("type", "text/javascript")
        scriptEle.setAttribute("src", "/_layouts/15/" + filename);
        document.getElementsByTagName("head")[0].appendChild(scriptEle)

    }
    // Render and initialize the client-side People Picker.
    function initializePeoplePicker(eleId) {
        // Create a schema to store picker properties, and set the properties.
        var schema = {};
	try {
        	schema['PrincipalAccountType'] = 'All';
	        schema['SearchPrincipalSource'] = 15;
        	schema['ResolvePrincipalSource'] = 15;
	        schema['AllowMultipleValues'] = true;
	        schema['MaximumEntitySuggestions'] = 50;
        	schema['Width'] = '200px';
	        // Render and initialize the picker. 
        	// Pass the ID of the DOM element that contains the picker, an array of initial
	        // PickerEntity objects to set the picker value, and a schema that defines
        	// picker properties.
	        SPClientPeoplePicker_InitStandaloneControlWrapper(eleId, null, schema);
	}
	catch(err){
		console.log(err.message);
	}

    }

...
Рейтинг: 0 / 0
Undefined
    #40086526
Фотография Relic Hunter
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
весь код

Код: javascript
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
$(document).ready(function () {

    RegisterScriptFiles('clienttemplates.js');
    RegisterScriptFiles('clientforms.js');
    RegisterScriptFiles('clientpeoplepicker.js');
    RegisterScriptFiles('autofill.js');

    function RegisterScriptFiles(filename) {
        var scriptEle = document.createElement('script');
        scriptEle.setAttribute("type", "text/javascript")
        scriptEle.setAttribute("src", "/_layouts/15/" + filename);
        document.getElementsByTagName("head")[0].appendChild(scriptEle)

    }
    // Render and initialize the client-side People Picker.
    function initializePeoplePicker(eleId) {
        // Create a schema to store picker properties, and set the properties.
        var schema = {};
	try {
        	schema['PrincipalAccountType'] = 'All';
	        schema['SearchPrincipalSource'] = 15;
        	schema['ResolvePrincipalSource'] = 15;
	        schema['AllowMultipleValues'] = true;
	        schema['MaximumEntitySuggestions'] = 50;
        	schema['Width'] = '200px';
	        // Render and initialize the picker. 
        	// Pass the ID of the DOM element that contains the picker, an array of initial
	        // PickerEntity objects to set the picker value, and a schema that defines
        	// picker properties.
	        SPClientPeoplePicker_InitStandaloneControlWrapper(eleId, null, schema);
	}
	catch(err){
		console.log(err.message);
	}

    }

    var workPhone = '';
    var workPhone2 = '';
    var pictureURL = ''; 	

    function GetUserProperty(prop,user) {
        console.log("USER=" + user);
        $.ajax({
            url: "/_api/SP.UserProfiles.PeopleManager/getuserprofilepropertyfor(accountname=@v,%20propertyname='" + prop + "')?@v=%27i%3A0%23.w%7C" + user + "%27",
            method: "GET",
	    async: false,
            headers: {
                "accept": "application/json;odata=verbose"
            },
            success: function (data) {
		if (prop=="WorkPhone"){
			workPhone = data.d.GetUserProfilePropertyFor;
		}
		if (prop=="WorkPhone2"){
			workPhone2 = data.d.GetUserProfilePropertyFor;
		}
		if (prop=="PictureURL"){
			pictureURL = data.d.GetUserProfilePropertyFor;
			if (pictureURL=='') pictureURL= "/Style Library/Images/user_profile.png";

		}
            },
            error: function (err) {
                alert(JSON.stringify(err));
            }
        });

    }

    function GetPeoplePickerValues(eleId) {
        var toSpanKey = eleId + "_TopSpan";
        var peoplePicker = null;

        // Get the people picker object from the page.
        //var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;
        var ClientPickerDict = this.SPClientPeoplePicker.SPClientPeoplePickerDict;
        // Get the people picker object from the page.
        for (var propertyName in ClientPickerDict) {
            if (propertyName == toSpanKey) {
                peoplePicker = ClientPickerDict[propertyName];
                break;
            }
        }
        if (peoplePicker != null) {
            // Get information about all users.
            var users = peoplePicker.GetAllUserInfo();
            var userInfo = '';
            for (var i = 0; i < users.length; i++) {
                var user = users[i];
                GetUserProperty("WorkPhone", user['Description']);
                GetUserProperty("WorkPhone2", user['Description']);
                GetUserProperty("PictureURL", user['Description']);
                userInfo += '<div style="width: 80px; float:left;"><img src="' + pictureURL + '" height="78" width="78"></div>' 
		+ '<div><h3>' + user['DisplayText'] + '</h3>' 
		+ '<h4> ' + user['EntityData'].Title + '</h4></div>'
		+ '<hr>'
		+ '<h5><span class="glyphicon glyphicon-earphone" aria-hidden="true"></span> ' + '<a href="tel:' + workPhone + '">' + workPhone + '</a>' 
		+ ' <span class="glyphicon glyphicon-phone-alt" aria-hidden="true"></span> ' + '<a href="tel:' + workPhone2 + '">' + workPhone2 + '</a>' 
                + ' <span class="glyphicon glyphicon-phone" aria-hidden="true"></span> ' + '<a href="tel:' + user['EntityData'].MobilePhone + '">' + user['EntityData'].MobilePhone + '</a>' + '</h5>' 
		+ '<h5><span class="glyphicon glyphicon-home" aria-hidden="true"></span> ' + user['EntityData'].Department + ' <span class="glyphicon glyphicon-envelope" aria-hidden="true"></span> ' + '<a href="mailto:' + user['EntityData'].Email + '">' + user['EntityData'].Email + '</a>' + '</h5>'
		+ ";#";
            }
            return userInfo;
        }
        else
            return '';
    }

    $.fn.spPeoplePicker = function () {
        var eleId = $(this).attr('id');
        ExecuteOrDelayUntilScriptLoaded(function () { initializePeoplePicker(eleId); }, 'sp.core.js');
    };

    // Query the picker for user information.
    $.fn.getUserInfo = function () {
        var eleId = $(this).attr('id');
        var spUsersInfo = GetPeoplePickerValues(eleId);
        return spUsersInfo.slice(0, -2);
    }

});

...
Рейтинг: 0 / 0
Undefined
    #40086965
alectr
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Если честно то не очень понял иерархию кто что грузит и вызывает :) В любом случае попробуйте сделать так:

1) Создайте js файл (допустим debug.js) с таким содержимым:
Код: javascript
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
window.tempFunc = undefined;

Object.defineProperties(
    window, 
    { 
        SPClientPeoplePicker_InitStandaloneControlWrapper: {
            get: function() { 
                return function(...args) {
                    debugger; /* при каждой попытке вызвать функцию, дебагер остановится здесь */
                    if (this.tempFunc) {
                        return this.tempFunc.apply(this, args);
                    }
                }
            },
            set: function(value) {
                debugger; /* при каждой попытке заасайнить функцию, дебагер остановится здесь */
                this.tempFunc = value;
            }
       }
    }
);



2) Добавьте его куда-нибудь в начало вашего входного html файла <head><script src="./debug.js"></script></head>

3) В браузере откройте dev tools и запускайте ваше приложение. Все обращения к функции SPClientPeoplePicker_InitStandaloneControlWrapper будут остановлены дебагером. Соответственно можно будет посмотреть кто обратился к функции раньше чем ее записали. Если что, то смотреть можно с помощью call stack вызовов в sources tab в dev tools.
...
Рейтинг: 0 / 0
Undefined
    #40087452
Фотография Relic Hunter
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
вопщем, переписал код. вынес вот эти стоки наверх из блока $(document).ready и все стабильно заработало

Код: javascript
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
    RegisterScriptFiles('clienttemplates.js');
    RegisterScriptFiles('clientforms.js');
    RegisterScriptFiles('clientpeoplepicker.js');
    RegisterScriptFiles('autofill.js');

    function RegisterScriptFiles(filename) {
        var scriptEle = document.createElement('script');
        scriptEle.setAttribute("type", "text/javascript")
        scriptEle.setAttribute("src", "/_layouts/15/" + filename);
        document.getElementsByTagName("head")[0].appendChild(scriptEle)

    }

...
Рейтинг: 0 / 0
7 сообщений из 7, страница 1 из 1
Форумы / HTML, JavaScript, VBScript, CSS [игнор отключен] [закрыт для гостей] / Undefined
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]