[英]Not able to store value inside a global variable
我正在使用setInterval方法阅读Rss feed并向用户显示通知,我想确保我存储了最新的feed标题,以使用户不会再次收到同一标题的多个通知。 所以我在notification.js的顶部声明了一个全局变量global_Rsstitle 。 现在,我尝试将entry_title的值传递给全局变量,在调用setinterval方法之后,该值不会保留在全局变量中。 有没有更好的方法来存储entry_title的值并在每次调用setInterval方法时进行检查,以避免对同一标题的多次通知。
我的notification.js
/** global variable **/
var global_Rsstitle;
/** end global variable **/
function get_rss1_feeds() {
var Rss1_title = getRss("http://rss.cnn.com/rss/cnn_topstories.rss", function(entry_title) {
if(global_Rsstitle != entry_title)
global_Rsstitle = entry_title;
console.log('test',global_Rsstitle); // the value is outputed but global var is not working
});
console.log('test1',global_Rsstitle); // outputted as undefined ??
}
google.load("feeds", "1");
google.setOnLoadCallback(function () { setInterval(get_rss1_feeds, 5000); });
我的jsRss.js文件
function getRss(url, callback){
if(url == null) return false;
// Our callback function, for when a feed is loaded.
function feedLoaded(result) {
if (!result.error) {
var entry = result.feed.entries[0];
var entry_title = entry.title; // need to get this value
callback && callback(entry_title);
}
}
function Load() {
// Create a feed instance that will grab feed.
var feed = new google.feeds.Feed(url);
// Calling load sends the request off. It requires a callback function.
feed.load(feedLoaded);
}
Load();
}
您定义了一个名为global_Rsstitle;
的变量global_Rsstitle;
但是在您的代码中,您使用Rsstitle
。 他们是两个不同的东西
您不应该设置global_Rsstitle
而不是Rsstitle
吗?
var global_Rsstitle;
/** end global variable **/
function get_rss1_feeds() {
var Rss1_title = getRss("http://rss.cnn.com/rss/cnn_topstories.rss", function(entry_title) {
if(global_Rsstitle!= entry_title)
global_Rsstitle = entry_title;
console.log('test',global_Rsstitle); // the value is outputed but global var is not working
});
}
UPDATE
您确实意识到,直到响应返回,您才能使用该变量,对吗?
换句话说,您不能这样做:
get_rss1_feed();
alert(global_Rsstitle);
因为会在读取提要和分配变量之前触发警报。更糟糕的是,您会延迟执行间隔。
在声明var global_Rsstitle;
,您永远不会为其分配任何内容。 它必须在某种表达的LHS上。 在变量中添加global_
并不会使它成为全局变量。 在函数外部定义它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.