Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use Javascript constructor methods in a jQuery statement?

I can't figure out how to use a Javascript constructor method in a jQuery .click method. I'm trying to get a button's function to change dynamically based on a constructor. Here's the set up:

<button onclick="">
</button>

needs to call a method that changes depending on another button. The following is my broken code:

    function GloveMode (name , array) {

        this.colorArray = array;

        this.displaySettings = function(){

            //Title
            $("#displayTitle").text(this.name);
            //Display Color Set
            $("#displayColors").empty();


            //Totally Broken
            $("#upArrow").click( function(){

                addColor();

            }); 

        };

        this.addColor = function(){

            console.log(this.colorArray.length);

        };
    };

I can't figure out how to get $("#upArrow").click() to call this.colorArray properly, or how to call this.addColor() in the .click() method! Please help.

like image 292
Joshua Ho Avatar asked Nov 20 '15 16:11

Joshua Ho


1 Answers

Your Problem is that "this" means something different in each function body. So save the wanted "this" to a variable e.g. "self" and use that.

function GloveMode (name , array) 
{
    var self = this;
    this.colorArray = array;
    this.displaySettings = function()
    {
      //Title
      $("#displayTitle").text(this.name);
      //Display Color Set

      $("#displayColors").empty();

      //Totally Broken
      $("#upArrow").click( function()
      {
         self.addColor();
      }); 

    };

    this.addColor = function()
    {
       console.log(self.colorArray.length);
    };
};
like image 71
Peter Paul Kiefer Avatar answered Oct 07 '22 12:10

Peter Paul Kiefer