Having Issue on Assigning Functions to JavaScript Object

50 views Asked by At

I have an JS Object like

var map = {
    prov1: { paper.path("M182.89887,371.5666L18,.... },
    prov2: { paper.path("M182.89887,371.5666L18,.... },
    prov3: { paper.path("M182.89887,371.5666L18,....}
};

now I need to assign some function to each of theses properties like

 $(map.prov1).hover({
   alert("You Assigned A Task to prov1");
});

in a working example it should be like

 $(prov1).hover({
   alert("You Assigned A Task to prov1");
});

but as you know I can not get access to $(prov1) directly and $(map.prov1) returns as [object object]!

Can you please let me know how to get the name and not the value of the object to run the function?

2

There are 2 answers

0
Ian On BEST ANSWER

I think you are trying to overcomplicate it by using jquery here, when its not needed.

You can simply do...


var paper = new Raphael('test', 200, 200);

var attrs = { fill: 'blue' }

var map = {
    prov1: paper.rect(10,10,20,20).attr( attrs ) ,
    prov2: paper.rect(40,40,50,60).attr( attrs ) ,
    prov3: paper.rect(50,60,70,80).attr( attrs )
};

map.prov1.click( function() {  alert('Hi Im prov1') } ); 

jsfiddle

If you needed to iterate over the object, you could do something like

Object.keys( map ).forEach( function( el ) { 
    map[el].click( function() { alert('Hi, Im ' + el) } ); 
} );

jsfiddle method with iteration if needed

4
Aman On

Do you need something like this?

var map = {
    prov1: function() { return paper.path("M182.89887,371.5666L18,.... ")},
    prov2: function() { return paper.path("M182.89887,371.5666L18,.... ")},
    prov3: function() { return paper.path("M182.89887,371.5666L18,....")}
};

map.prov1();