Javascript-форум (https://javascript.ru/forum/)
-   Events/DOM/Window (https://javascript.ru/forum/events/)
-   -   Работа с обьектом и this (https://javascript.ru/forum/events/67426-rabota-s-obektom-i.html)

Dencho 17.02.2017 00:45

Работа с обьектом и this
 
Привет всем. не могу решить один вопрос, Есть обьект:
var menu_js = {
        url:"js/menu.json",
        json_data: 'empty',
        menu: '',
        init:function(){

            this.load_json(function( jsonData ) {
                JSON.parse(jsonData);
                //как тут данные присвоить json_data
            });

            console.log(this.json_data) // выводится empty

            this.draw_menu(this.json_data) //отрисовка меню
        },
        load_json:function(ready){
            var xhr = new XMLHttpRequest();
            xhr.open( 'GET', this.url, true );
            xhr.send();
            xhr.onreadystatechange = function() {
                if (xhr.readyState != 4) return;
                if (xhr.status != 200) {
                    console.log(xhr.status + ': ' + xhr.statusText);
                } else {
                   ready(xhr.responseText);
                }
            }
        },
        draw_menu:function(){
            //....
        }
}

Данные загружаются всё норм но я не могу их присвоить json_data. В чем моя ошибка?. В этой теме я только разбираюсь, прошу сильно не пинать:)

Alexandroppolus 17.02.2017 01:08

var menu_js = {
        url:"js/menu.json",
        json_data: 'empty',
        menu: '',
        init:function(){

            this.load_json(function( jsonData ) {
                this.json_data = jsonData;

                this.draw_menu(); //отрисовка меню
            });
        },
        load_json: function(ready){
            var self = this;
            var xhr = new XMLHttpRequest();
            xhr.open( 'GET', this.url, true );
            xhr.send();
            xhr.onreadystatechange = function() {
                if (xhr.readyState != 4) return;
                if (xhr.status != 200) {
                    console.log(xhr.status + ': ' + xhr.statusText);
                } else {
                   ready.call(self, JSON.parse(xhr.responseText));
                }
            }
        },
        draw_menu: function(){
            // здесь уже получена this.json_data
        }
}

Dencho 17.02.2017 16:09

Спасибо большое помогло


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