Question

Here is what I have:

function HelloFeed(WPFeedUrl) {
    var title, articles;
    WinJS.xhr({ url: WPFeedUrl }).then(function (rss) {
        title = rss.responseXML.querySelector("title").textContent;
        var items = rss.responseXML.querySelectorAll("item");

        for (var n = 0; n < items.length; n++) {
            var article = {};
            article.title = items[n].querySelector("title").textContent;
            var thumbs = items[n].querySelectorAll("content");
            article.content = items[n].querySelector("encoded").textContent;
            if (thumbs.length > 1) {
                article.thumbnail = thumbs[thumbs.length - 1].attributes.getNamedItem("url").textContent;
            }
            else {
                var firstindex = article.content.indexOf("<img");
                if (firstindex !== -1) {
                    var secondindex = article.content.indexOf("src=", firstindex) + 5;
                    var thirdindex = article.content.indexOf("\"", secondindex);
                    article.thumbnail = article.content.slice(secondindex, thirdindex);
                }
            }
            BasketballItems.push({ group: BasketballGroups[0], title: "hello", content: "h", backgroundImage: lightGray });
        }
    });
}

If I place BasketballItems.push({ group: BasketballGroups[0], title: "hello", content: "h", backgroundImage: lightGray }); outside the WinJS.xhr block of code, it successfully adds an element to the array BasketballItems, however if I put it inside that big block of code, it doesn't function. I am calling the function like this: HelloFeed("http://allball.blogs.nba.com/feed/");

What am I doing wrong?

Was it helpful?

Solution

It appears to be the classic mistake of trying to use data that is processed after an asynchronous operation before the asynchronous operation has finished and run the callback. Whatever code needs BasketballItems should be called as part of that code block. For example:

BasketballItems.push({ group: BasketballGroups[0], title: "hello", content: "h", backgroundImage: lightGray });
myOtherCode(BasketballItems);

and then put the code that needs to know about those items in that function. It's just another callback.

function myOtherCode(items) {
  console.log(items); // <--- code in here knows about the push, since it occurs in the callback chain after the asynchronous operation (WinJS.xhr)
}

Depending on the scope, you may not need to pass in BasketballItems as I did there. It looks like you can just access it implicitly, but I don't recommend having such non-encapsulated variables.

To clarify my meaning, you might also be able to just do this in the callback:

function myOtherCode() {
  console.log(BasketballItems);
}

Of course, you could also not use a function and just dump all of your code right there instead, but it's better to try to break your code up more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top