I need to check something with request
on every page and load widget when data is correct.
The problem is strange - widget is loaded twice the second time I reload page.
var widgets = require("widget");
var self = require("self");
var tabs = require("tabs").on("ready", start_script);
var request = require("request").Request;
function start_script(argument)
{
request({
// checking something
url: "http://localhost/check.php",
onComplete: function (response)
{
if ( typeof widget == "undefined" )
{
// make widget
var widget = widgets.Widget({
id: "xxxxxxxx",
label: "zzzzz",
contentURL: self.data.url("http://www.google.com/favicon.ico")
});
}
}
}).get();
}
It works for first page. After reloading it, it throws error: This widget ID is already used: xxxxxxxx
.
Why does it load widget second time, even if I have if ( typeof widget == "undefined" )
?
If I made it without request
, everything is working great. What did request
change?
Because variable widget
is not yet defined / unknown in the if
condition. You need to use proper scoping.
You can try:
var widgets = require("widget");
var self = require("self");
var tabs = require("tabs").on("ready", start_script);
var request = require("request").Request;
var widget; //define widget here so that it is visible in the if condition.
function start_script(argument)
{
request({
// checking something
url: "http://localhost/check.php",
onComplete: function (response)
{
if ( typeof widget == "undefined" ) //using the variable here
{
// make widget
widget = widgets.Widget({
id: "xxxxxxxx",
label: "zzzzz",
contentURL: self.data.url("http://www.google.com/favicon.ico")
});
}
}
}).get();
}
or
Check for the presence of a widget with id xxxxxxxx
inside the if
condition.