0

I have one complicated situation with JavaScript. I have created object. This object loads JS, CSS files dinamicly( see load function ). My problem is that I want to add onload event when object file is loaded and change some values in that object.

My object constructor:

function lib( type, url )
{
  //Varaibles
  this.URL = url;        //Files url
  this.TYPE = type;      //Files type( can by CSS or JS )
  this.READY = false;    //Files loaded status
  //Functions
  this.load = load;      //Method, which is called to start loading file
  this.status = status;  //Return READY status( false or true )
}

So I'm trying on file load change READY status. This thing I want to set in load function. For now I have this load function:

function load()
{
    var object = this;
    switch ( this.TYPE.toUpperCase() )
    {
        case "JS" :
        {
            var script = document.createElement( "script" );
            script.setAttribute( "type", "text/javascript" );
            script.setAttribute( "src", this.URL );
            document.getElementsByTagName( "head" )[0].appendChild( script );


            if( navigator.appName == "Microsoft Internet Explorer" )
            {
                script.onreadystatechange = function () { this.READY = true; };
            } else {
                script.onload =function () { this.READY = true; };
            }

            break;
        }
        ( Here should be CSS loading... )
    }
}

So guys, I need to see my code and see what I do wrong

gedO
  • 548
  • 2
  • 7
  • 24

2 Answers2

3

When the event handler is called its done in the script element context and the this keyword points to it use object.READY = true; instead.

Prusse
  • 4,287
  • 2
  • 24
  • 29
  • +1 More: *[You must remember `this`](http://blog.niftysnippets.org/2008/04/you-must-remember-this.html)* (Disclosure: my blog, but it's not monetized or anything nor likely to be) – T.J. Crowder Jul 26 '11 at 16:08
1

If your problem is with 'readystatechange' event, you can try to fix it like this:

script.onreadystatechange = function () {
    if (this.readyState == 4)
        object.READY = true;
};
lazyhammer
  • 1,228
  • 1
  • 11
  • 14
  • I don't started support for IE, but thank you for your answer. I think I will use it :) – gedO Jul 26 '11 at 16:39