1

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?

1
  • Because widget object is not yet defined / unknown in the if condition.
    – Ezhil V
    Apr 28, 2013 at 13:36

1 Answer 1

3

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.

1
  • totaly forget about scope!
    – Qiao
    Apr 28, 2013 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.