Guido Rossi
Guido Rossi

Reputation: 57

Basic OOP & jQuery - Why am I getting TypeError?

here's my basic code:

JS:

jQuery(function($)
{
    function MyTest() {}

    MyTest.prototype =
    {
        myMethod: function()
        {
            $(this).append("<div id='myId'></div>");
        }
    }

    $(document).ready(function()
    {
        var myTest1 = new MyTest();

        $("#anelement").click(function()
        {
            myTest1.myMethod();
        });
    });
});

HTML:

<div id='anelement'></div>

Clicking on "anelement", JS console returns:

TypeError: e is undefined ... jquery.min.js (line 5)

...and it doesn't append "myId" - why?

Thanks

Upvotes: 0

Views: 128

Answers (1)

Kevin B
Kevin B

Reputation: 95023

You need to somehow pass the clicked element into your method. Here is one way to do it:

jQuery(function ($) {
    function MyTest() {}

    MyTest.prototype = {
        myMethod: function (el) {
            $(el).append("<div id='myId'></div>");
        }
    }

    $(document).ready(function () {
        var myTest1 = new MyTest();

        $("#anelement").click(function () {
            myTest1.myMethod(this);
        });
    });
});

You could also use .call to execute your method with the given context, however you then lose access to instance methods and variables.

jQuery(function ($) {
    function MyTest() {}

    MyTest.prototype = {
        myMethod: function () {
            $(this).append("<div id='myId'></div>");
        }
    }

    $(document).ready(function () {
        var myTest1 = new MyTest();

        $("#anelement").click(function () {
            myTest1.myMethod.call(this);
        });
    });
});

or simply

jQuery(function ($) {
    function MyTest() {}

    MyTest.prototype = {
        myMethod: function () {
            $(this).append("<div id='myId'></div>");
        }
    }

    $(document).ready(function () {
        var myTest1 = new MyTest();

        $("#anelement").click(myTest1.myMethod);
    });
});

Upvotes: 1

Related Questions