Crouzilles
Crouzilles

Reputation: 813

Undefined javascript variable using kineticjs

I have always thought that if you declared a javascript var outside a function, it would then be available and used within that function if you needed it.

I have a problem with the code below, when I click a button which triggers the get_value function the console tells me that the tween variable is undefined.

    <script>
        $(document).ready(function() 
        {
            var timeout_val = 0;

            var stage = new Kinetic.Stage({
                container: 'stage',
                width: 940,
                height: 50
            });
            var layer = new Kinetic.Layer();

            var line = new Kinetic.Line({
                points: [10, 10, 100, 10],
                stroke: '#FF0000'
            });

            layer.add(line);
            stage.add(layer);

            var xTo = stage.getWidth() - 10;

            var tween = new Kinetic.Tween({
                node: line,
                duration: 5,
                points: [10, 10, xTo, 10]
            });
        });

        function get_value(){
            $.ajax({
                type: "GET",
                url: "players.php",
                data: {}
            }).done(function( result ) {
                if (result != "Timeout Error") {
                    $("#players").html(result);
                }
                $("table").tablesorter({widgets: ["zebra"], sortList: [[1,1], [0,0]]});
                timeout_val = window.setTimeout(get_value, 5000);
            });
            tween.reset();
            tween.play();
        }
    </script>

This script block is inside the head of my page if that makes any difference.

I then call the get_value function with a simple input button written like this.

<input type="button" name="submit" id="submit" value="submit" onClick = "get_value();" />

I am at a loss as to why this isn't working, if you could please enlighten me

Thank you Crouz

Upvotes: 0

Views: 132

Answers (1)

Jacob
Jacob

Reputation: 78840

tween is defined within the inline function used in your call to $(document).ready. It is therefore not in scope for get_value.

If you defined get_value from inside the same ready handler, then it would see that variable. Or if you moved tween to outside of its ready handler so it was global, it would be seen then as well. As it is now, it's in a completely separate scope.

Upvotes: 1

Related Questions