Search code examples
javascriptclassoopkineticjs

Use a global variable inside a handler function in kineticjs


I have a global function called analysis declared at the beginning of a javascript file

then I have a function that is used as a handler for a contentClicked on stage event.

//global
var analysis

function onStageContentClicked(event){
    //I use analysis
    var pointId = "a point name";
    if (analysis.hasPoint(pointId)){
        //....do some more things
    }
    //...and more...
}


$(document).ready(function(){
    if ($("select").val() === "Downs"){

         analysis = Downs(23);
        stage.on("contentClicked", onStageContentClicked);
    }

});

Inside onStageContentClicked on the if part I get a cannot find hasPoint of undefined. Meaning that my Downs object is not set. I have a Downs Class created in a different js file called analysis.js. I used prototype to create class

function Downs (maxPoints){
    this.points = {};
    this.maxPoints = maxPoints
    this.go_apostrophe;
    this.go_apoAngle;
    this.bicetrix = [];


}


Downs.prototype.addPoint = function (pos, pointId){
    this.points[pointID] = {'x':pos.x, 'y':pos.y};
}

Downs.prototype.pointExists = function (pointId){
    var pointIds = Object.keys(this.points);
    for (var i=0; i< pointIds.length; i++){
        if (pointId === pointIds[i]){
            return true;
        }
    }
    return false;
}
//etc

But I can't create the object. I bet I am doing something wrong with the calss object. Can you help me please?I have added my analysis.js before the js file that contains main document.ready code.


Solution

  • Downs is a constructor, so you need to call it with new:

    analysis = new Downs(23);