thpl
thpl

Reputation: 5910

Share Javascriot object across jQuery plugin

Currently I'm experiencing a little logical problem. Assume I have an object where I store several mapdata for my tileengine and a jQuery extension which calculates the x and y positions of the clicked tile.

    $(document).ready(function(){   

        var mapdata = {
            dimensions: {x: 10, y: 10},
            tileSize: 32
        };

        $.fn.getpos = function(type){
            var xpos = $(this)%mapdata.dimensions.y;
            var ypos = Math.floor($(this)/mapdata.dimensions.y);

            else if(type == 'x')
                return xpos;
            else if(type == 'y')
                return ypos;
            else
                return {x: xpos, y:ypos}
        }       

        $('.tile').click(function(){
            console.log($($(this).index('.tile')).getpos());
        });
    });

The problem is clear to me. I'm trying to access the mapdata object which is not available within the scope of getpos(). Is there a way I can acomplish this? Otherwise I'd need to pass my mapdata to every extension I'm going to make.

Thank you in advance. Sincerly, Thomas

Upvotes: 0

Views: 91

Answers (2)

d1pr3d
d1pr3d

Reputation: 76

When you define the getpos() function it inherits the scope at the very same moment, so mapdata as it is defined now should be visible to it.

Try console.log($(this)) inside getpost(). Probably it has value what you don't expect with math operations.

Upvotes: 2

nagylzs
nagylzs

Reputation: 4180

When a global variable is set, it is assigned to the window object. Try window.mapdata.

Upvotes: 1

Related Questions