Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Скоуп в JS ООП (https://javascript.ru/forum/misc/63500-skoup-v-js-oop.html)

Blondinka 11.06.2016 12:28

Скоуп в JS ООП
 
Добрый день.

Делаю форму. Создала автозаполнение города, страны и региона данными. Проблема в том, что я присваиваю переменной значение, вывожу его в консоли (работает), но когда пытаюсь записать эти же данные из другой части программы - ничего не получается.
var forma = {
	model:{
	    userLocationCity: "",
	    userLocationCountry: "",
	    userLocationRegion: "",
	    getUserLocation: function(){
	    	$.getJSON('http://ipinfo.io', function(data) {
                if (data) {// If data exist.
				    forma.model.userLocationCity = data.city;
				    console.log(forma.model.userLocationCity);//Work
				    forma.model.userLocationCountry = data.country;
				    forma.model.userLocationRegion = data.region;
                } else {
                
                }
            });
	    }		
	},
	view:{
		render: function(){
			//Put data from the model in the form.
			$("input[name~='country']").val("Ukraine"); //Works.
			$("input[name~='city']").val(forma.model.userLocationCity); //Doesn't work
			$("input[name~='region']").val(forma.model.userLocationRegion); //Doesn't work
			alert("It's allive! "+forma.model.userLocationCountry); //Doesn't work
		}
	},
	controller: {
		init: function(){
			forma.model.getUserLocation();
			forma.view.render();
			
		}
	}

};


forma.controller.init();

<form method="POST" action="">
            <input type="text" name="name" placeholder="John" required />
		    <input type="text" name="surname" placeholder="Smith" required />
			<hr/><!--Put the data from JS-model inside-->
		    <input type="text" name="country" placeholder="USA" required />
			<input type="text" name="region" placeholder="California" required />
			<input type="text" name="city" placeholder="Mountain View" required />
			
			<input type="submit" value="Finish him!">
		</form>

Почему не работает?

destus 11.06.2016 13:21

Blondinka,
А так нельзя?
var forma = {
	model:{
	    userLocationCity: "",
	    userLocationCountry: "",
	    userLocationRegion: "",
	    getUserLocation: function(){
	    	$.getJSON('http://ipinfo.io', function(data) {
                if (data) {// If data exist.
	 forma.model.userLocationCity = data.city;
				    console.log(forma.model.userLocationCity);//Work
				    forma.model.userLocationCountry = data.country;
				    forma.model.userLocationRegion = data.region;
                                    forma.view.render();
                } else {
                
                }
            });
	    }		
	},
	view:{
		render: function(){
			//Put data from the model in the form.
			$("input[name~='country']").val("Ukraine"); //Works.
			$("input[name~='city']").val(forma.model.userLocationCity); //Doesn't work
			$("input[name~='region']").val(forma.model.userLocationRegion); //Doesn't work
			alert("It's allive! "+forma.model.userLocationCountry); //Doesn't work
		}
	},
	controller: {
		init: function(){
			forma.model.getUserLocation();			
		}
	}

};
forma.controller.init();

Blondinka 11.06.2016 14:03

destus, так работает, но хочу понять почему данные переменной не отображаются при вызове её из view.

destus 11.06.2016 14:05

Blondinka,
потому что так устроен асинхронный мир

Coriolan161 11.06.2016 14:36

Blondinka,
В процессе работы скрипта

1) у тебя при вызове getUserLocation происходит запрос данных.

2) ты не блокируешь исполнение кода, благодаря колбеку function (data) {}

3) Выполнение не останавливается и происходит вызов view.render(). А он берет userLocationCity == ""

Короче у тебя строки userLocationCity и т.д не обновляются.
Поэтому сделай так как МиккиМаус предложил.


Часовой пояс GMT +3, время: 16:33.