0

I am trying to build a generic ajax loader, while ajax is running a lightbox with animated "Loading" gif will be displayed.

I have some issues with scoping.

The code is:

var t=setTimeout( "s.d.dialog( 'destroy' )" ,(s.o.msgTime*1000));

The error is: "Uncaught ReferenceError: s is not defined"

;(function ($) { 
      $.loader = function (data, options) {
    return $.loader.impl.init(data, options);
  };

  $.loader.close = function (data) {
    $.loader.impl.close(data);
  };

  $.loader.create = function () {
    $.loader.impl.create();
  };

$.loader.defaults = {
        appendTo: 'body',
        autoCreate: true,
        msgTime: 5,
    };

$.loader.impl = {
    d: {},
    init: function(data, options){

        var s = this;
        s.o = $.extend({}, $.loader.defaults, options);

        if ((typeof data === 'object')&&!(data instanceof jQuery)&&data.url) {

            data.success = function(data, textStatus, jqXHR){ $.loader.close(); }
            data.error = function(jqXHR, textStatus, errorThrown){ $.loader.close('Error accessing server'); }
            $.ajax(data);
        }else if(s.o.autoCreate){
            s.create();
        }

        return s;
    },
    create: function() {
       var s = this;
       s.d = $('<div  id="dialog" style="display:hidden"><span style="width: 100%" id="loading_diag"><center><img src="http://www.mydomain.com/images/ajax-loader.gif" /></center></span></div>').appendTo(s.o.appendTo);
       s.d.dialog({ title: 'Loading ...', dialogClass: 'noTitleStuff', modal: true, draggable: false, resizable: false });

    },
    close: function(data)
    {
        var s = this;
        //alert(typeof s.d);
        if ((typeof data === 'string')&&data) {
            $("#loading_diag").hide();
            $("#dialog").html(data);

            var t=setTimeout( "s.d.dialog( 'destroy' )" ,(s.o.msgTime*1000));
        }else{
            s.d.dialog( "destroy" );
            }

        s.d= {};
    },
};

})(jQuery);

If anybody knows how to solve it please share.

The first and second solution did something but havent fixed it completely, now i am getting a different error: "Uncaught TypeError: Object # has no method 'dialog' $.loader.impl.close.s.d"

4

2 回答 2

2

This will make it work:

var t = setTimeout(function() { s.d.dialog('destroy'); }, s.o.msgTime * 1000);

When you pass a string into setTimout, then that string (code) executes in global code - and since s is a local variable, it is indeed not defined in global code.

于 2011-04-17T14:38:31.030 回答
1

当您将字符串传递给 setTimeout 时,字符串中的代码将在window对象的上下文中执行。由于window.s不存在,因此您会收到错误消息。您可以将闭包传递给 setTimeout 以将 s 变量保持在范围内,如下所示:

var t = setTimeout(function() {s.d.dialog('destroy'); }, s.o.msgTime * 1000);
于 2011-04-17T14:41:50.350 回答