PiousVenom
PiousVenom

Reputation: 6908

Uncaught TypeError: not a function, but the function exists

I have the following in my js file:

var Field_File = function( _ )
{
    var _objects = null;

    var Init = function( instance, json )
    {
         // load _objects
    }

    var ImgLoad = function( elem, type )
    {
        //do things with _objects
    }
}

Now in my PHP, I've got:

<img id="file_uploader2_button" src="http://localhost/img/icons/up.png" onload="Field_File.ImgLoad(this, 'img');">

I've verified that the JS is loading into my page properly, and I'm calling other JS functions via the same PHP page with no problems:

body onload="Field_File.Init( '1', {$json});"

But I currently get:

Uncaught TypeError: Field_File.ImgLoad is not a function

Am I missing something in this call?

Upvotes: 1

Views: 1774

Answers (2)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

Change the declaration of your module (a literal object) to

var Field_File = {
    Init: function( instance, json ){
    },
    ImgLoad: function( elem, type ){
        //do things
    }
}

If you want a scope to protect some private variables, use an IIFE:

var Field_File = (function(){
    var _objects = null;
    var Init = function( instance, json ){
         // load _objects
    }

    var ImgLoad = function( elem, type ){
        //do things with _objects
    }

    return {
        Init:Init,
        ImgLoad:ImgLoad
    }
})();

Many variations are possible, so what is important is to understand what happens here so that you can adapt it to your needs.

Upvotes: 3

Prawny
Prawny

Reputation: 123

Change ImageLoad to a property of Field_File using this. When declaring it with var here, you are somewhat simulating a private property.

var Field_File = function( _ )
    this.Init = function( instance, json )
    {
    }

    this.ImgLoad = function( elem, type )
    {
        //do things
    }
}

Upvotes: 1

Related Questions