Joe Slater
Joe Slater

Reputation: 2473

Passing param directly works, passing it within a object or array does not work

I have a function which looks like this

function myFunction(param)
{
    param.on('mouseover', function(){/*Do something*/});
}

var polygon = new Kinetic.Polygon({
    //My settings
});
myFunction(polygon);

This works absolutely fine. But when I pass polygon within an array or object like this I get the error.

function myFunction(param)
{
    for(var elem in param)
    {
        elem.on('mouseover', function(){/*Do something*/});
    }
}

var polygon = new Kinetic.Polygon({
    //My settings
});
myFunction([polygon]);

Error is (in console):

Uncaught TypeError: Object 0 has no method 'on'

What am I doing wrong?

Upvotes: 0

Views: 41

Answers (1)

Myrne Stol
Myrne Stol

Reputation: 11438

Javascript's for ... in loops work a little differently than you think. The values that are yielded by the statement are actually the properties of the object that is iterated over, which in case of an Array object are the array indexes.

The below should work:

function myFunction(array)
{
    for(var key in array)
    {
        elem = array[key]
        elem.on('mouseover', function(){/*Do something*/});
    }
}

See http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/ for some more examples.

Upvotes: 1

Related Questions