javascripteventsdom-eventskineticjs

Is possible to have an event linked to object's own parameter?


I have an object (lets say a circle) with specific parameters (x,y and radius).

var circle = new Kinetic.Circle({
        x: 100,
        y: 100,
        radius: 20
}

The radius of the circle is thereafter dynamically changed by the user. Now I want a listener that continuously observes the radius, and every time the radius goes below 5, it deletes the circle. Something like:

circle.on("radiusLessThanFive",function (e) {
this.remove();
}

So how do I configure this radiusLessThanFive event that constantly listens to the radius of the circle?


Solution

  • Well, unfortunately, there isn't something built in that would do that. So you just have to make it part of your application logic.

    Let's say you have a layer called shapesLayer. You can do:

    function radiusLessThanFive(){
        var circles = shapesLayer.get('.circle'); // I can't remember the getting all circles syntax, but something like this
        for ( var i=0; i<circles.length; i++) {
            if(cicrles[i].getRadius() < 5 ){
                circles[i].remove();
                shapesLayer.draw();
            }
        }
    }
    

    While this is not the most efficient solution ever, it gets the job done... unless you know how to create your own custom events in javascript (which would have to do the same thing as the above function anyways).

    In case you'd like to take the custom event road, here is a link: http://www.sitepoint.com/javascript-custom-events/

    Edit: regarding comment below

    function radiusLessThanFive(myCircle){ //function which checks radius of single circle and deletes if less than 5
            if(myCircle.getRadius() < 5 ){
                myCircle.remove();
                myCircle.getParent().draw();
            }
        }
    }