Ron van der Heijden
Ron van der Heijden

Reputation: 15070

Why jQuery.data() bugs with Raphael svg paths?

I have a problem with jQuery .data() and Raphael's SVG path().

I wrote a little example to explain.

paper = Raphael(0, 0, 600, 600)
polygon = paper.path('M19,20L24,83L106,62L112,23Z')
polygon.data('test', 'I need this info later!')
polygon.attr({"fill":"orange"})

$(document).on('click', onClick)

function onClick() {
    console.log('click')
    if(event.target.nodeName === 'path') {
        // how do i get data('test') ?

        // console.log(this.data('test')) // Uncaught TypeError: Object #<HTMLDocument> has no method 'data' 
        console.log($(this).data('test')) // undefined
        // console.log(event.target.data('test')) // Uncaught TypeError: Object #<SVGPathElement> has no method 'data' 
        console.log($(event.target).data('test')) // undefined

        // But jquery.remove() does work?
        $(event.target).remove()

    }
}

As you can see, I made a polygon, filled it with a color, and added an event listener to the document. On every click I check the target. If this is a polygon, I want to get its data.

Notice that in my real code, I generate tons of polygons like this. So a simple polygon.data() won't help. My only solution is using the event.target as reference. Example of multiple polygons

How can I receive the data values?

Upvotes: 3

Views: 593

Answers (1)

Neil
Neil

Reputation: 8111

You were close, you just need the node wrapped in a jquery object to set the data first:

$(polygon.node).data('test', 'I need this info later!');

I updated your jsfiddle to show it working.

Upvotes: 2

Related Questions