Question

Is there a way to get the paper for an element by referencing the element?

I'm creating elements in a loop and with each element i'm creating a new Raphael(...). See sample below.

Basically I want to stop the animation on click, but paper is undefined and calling stop() on the element itself doesn't work either.

$.each(el,function(key,value)
{
    var li = $("<li>",{id:"item"+key).appendTo("#myUl");
    var ppr = new Raphael($("item"+key),get(0),48,48);
    //... do stuff like animate ...
    li.click(function()
    {
      console.log($(this).paper); //undefined
    })
})
Était-ce utile?

La solution

I was wondering about a closure like below to capture the paper, so when the anonymous func runs, it has the variable captured.

Note, I'm not sure this is the best method overall, something feels a bit clunky about creating a new paper each time, but just trying to address the specific issue.

Untested code, but if you can get it on a fiddle, I think it should be possible to sort.

$.each(el,function(key,value)
{
    var li = $("<li>",{id:"item"+key).appendTo("#myUl");
    var ppr = new Raphael($("item"+key),get(0),48,48);

    (function() {
      var myPaper = ppr; 
      li.click(function()
      {
        console.log(myPaper); 
      })
    })();
})

Autres conseils

You can also attach the paper to the element's "data" using https://api.jquery.com/data/

$.each(el,function(key,value)
{
    var li = $("<li>",{id:"item"+key).appendTo("#myUl");
    var ppr = new Raphael($("item"+key),get(0),48,48);
    li.data("paper", ppr ); // SAVE

    li.click(function()
    {
        console.log($(this).data("paper")); // LOAD
    })
})

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top