Search code examples
javascriptjquerysamsung-smart-tv

Return does not return Object


I've two javascript classes (Controller.js & Events.js). From Events.js i call a XML Parser in Controller.js. The Parser works but does not return anything:

SceneEvent.prototype.handleKeyDown = function (keyCode) {
    switch (keyCode) {
        case sf.key.ENTER:
            var itemList = null;    
            itemList = Controller.ParseXML("app/data/Event.xml");   
            alert("itemList = " + itemList);
    }
};

Controller.js looks like that:

Controller.ParseXML = function (url) {
    var itemList = null;

    $.ajax({
        type: "GET",
        url: url,
        dataType: "xml",
        async: false,
        success: function(xml) {
            $(xml).find("event").each(function() {
                var _id = $(this).attr("id");
                var _eventItemDay = $(this).find("eventItemDay").text();
                ...
                var _eventItemLocation = $(this).find("eventItemLocation").text();

                itemList = {
                    id: _id,
                    eventItemDay: _eventItemDay,
                    eventItemLocation: _eventItemLocation,
                    ...
                    eventItemLocation: _eventItemLocation
                };
            });
            return itemList;
        },
        error: function(xhr, ajaxOptions, thrownError){
            alert("XML ERROR");
            alert(xhr.status);
            alert(thrownError);
        }
    });
};

When I print out the itemList in Controller.js everything works fine. Any suggestions?


Solution

  • You have to return the value at the end of the ParseXML function, not at the end of the success function.

    Controller.ParseXML = function (url) {
        var itemList = null;
    
        $.ajax({
            type: "GET",
            url: url,
            dataType: "xml",
            async: false,
            success: function(xml) {
                $(xml).find("event").each(function() {
                    var _id = $(this).attr("id");
                    var _eventItemDay = $(this).find("eventItemDay").text();
                    ...
                    var _eventItemLocation = $(this).find("eventItemLocation").text();
    
                    itemList = {
                        id: _id,
                        eventItemDay: _eventItemDay,
                        eventItemLocation: _eventItemLocation,
                        ...
                        eventItemLocation: _eventItemLocation
                    };
                });
    
            },
            error: function(xhr, ajaxOptions, thrownError){
                alert("XML ERROR");
                alert(xhr.status);
                alert(thrownError);
            }
        });
    
        return itemList;
    };