JavaScript Callback Functions and Google Feed API

ε祈祈猫儿з 提交于 2019-12-22 14:54:23

问题


I'm trying to implement a few feeds into my site using a div-populating function. Previously, I had identical JavaScript code blocks through my page (one for each feed), but in the interest of being a good (or better) coder, I decided to stick the repetitive code into an external script file and run it with varying parameters instead.

Unfortunately, the feeds refuse to load with my new implementation, and I'm running out of ideas. I structured my callback function based on user ndp's interesting suggestions in question 9662168.

So, I have the following two functions in my external script file (minor code redaction for simplicity):

function populateRSSFeed(divID) {
    var targetDiv = document.getElementById(divID);
    return function callback(result) {
        if (!result.error) {
            var container = document.getElementById(targetDiv);
            var list = document.createElement('ul');
            <snip: div-population code here>
            container.appendChild(list);
        }
        else
            alert('Error fetching feeds!');
    }
}


function initializeRSSFeed(callback, targetFeed) {
    google.load('feeds','1');
    var feed = new google.feeds.Feed(targetFeed);
    var numEntries = 3;
    feed.setNumEntries(numEntries);
    feed.load(callback);
}

These functions are called as follows in my HTML:

<script>
    var callback = populateRSSFeed('feed-list-wrapper-1');
    initializeRSSFeed(callback, 'http://rss.cnn.com/rss/cnn_topstories.rss');
</script>

The error message I'm receiving makes me think that something is going wrong at the feed-loading stage, but I can't determine the cause.

Uncaught TypeError: Cannot read property 'Feed' of undefined

What do you guys think?


回答1:


It looks like you're not using setOnLoadCallback to wait for the Google scripts to load. That would explain why google.feeds is undefined (resulting directly in the error you're seeing).

Try using this script instead (I just followed the "Hello World" example in the Developers' Guide).

google.load('feeds','1');
function onGoogleReady() {
    var callback = populateRSSFeed('feed-list-wrapper-1');
    initializeRSSFeed(callback, 'http://rss.cnn.com/rss/cnn_topstories.rss');
}
google.setOnLoadCallback(onGoogleReady);


来源:https://stackoverflow.com/questions/12271308/javascript-callback-functions-and-google-feed-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!