Almog Dubin
Almog Dubin

Reputation: 329

ID with Javascript doesn't work as needed

in Raphaeljs, it wrote this line of code:(only relevant part is shown)

......
    sets.id = index;
    grid.hex[poly].click(
      function(e)
    {   
        var id=this.id
.....

It sets the id of the sets[] properly, but the id of "this" is the id of the path inside of the sets, the one that was clicked. I have to have the id of the sets. How can I accomplish that?

EDIT: I want "this" to be sets, not the path that was clicked.

Upvotes: 0

Views: 105

Answers (2)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

Bind function to sets

......
    sets.id = index;
    grid.hex[poly].click($.proxy(function(e){
         var id = this.id;
    }, sets);
.....

Or if you are not using jQuery.

//https://gist.github.com/978329
if(!Function.prototype.bind) {
   Function.prototype.bind = function(to){
        // Make an array of our arguments, starting from second argument
    var partial = Array.prototype.splice.call(arguments, 1),
        // We'll need the original function.
        fn  = this;
    var bound = function (){
        // Join the already applied arguments to the now called ones (after converting to an array again).
        var args = partial.concat(Array.prototype.splice.call(arguments, 0));
        // If not being called as a constructor
        if (!(this instanceof bound)){
            // return the result of the function called bound to target and partially applied.
            return fn.apply(to, args);
        }
        // If being called as a constructor, apply the function bound to self.
        fn.apply(this, args);
    }
    // Attach the prototype of the function to our newly created function.
    bound.prototype = fn.prototype;
    return bound;

}

grid.hex[poly].click(function(e){
         var id = this.id;
    }.bind(sets));

Upvotes: 1

pete
pete

Reputation: 25081

Have you tried?:

var id = this.parentElement.id

UPDATE:

From http://raphaeljs.com/:

Raphaël ['ræfeɪəl] uses the SVG W3C Recommendation and VML as a base for creating graphics. This means every graphical object you create is also a DOM object, so you can attach JavaScript event handlers or modify them later.

Assuming sets is a graphical object (and since it contains paths, I assume it is), then this should have a parentElement property to access.

If it doesn't work, you could also try accessing it as:

var id = sets.id;

which should work because of the closure.

Upvotes: 0

Related Questions