开发者

How to reference a Raphael canvas created dynamically?

I'm creating a jQ开发者_JS百科uery plugin that creates Raphael objects on the fly, let's say you do...

$("div").draw({
  type: 'circle',
  radius: '10',
  color: '#000'
})

And the plugin code (just as an example):

  $.fn.draw = function( options ) { 
  //settings/options stuff


   var width = $(this).width();
   var height = $(this).height();
   var widget = Raphael($(this)[0], width, height);
   var c = widget.circle(...).attr({...})

   //saving the raphael reference in the element itself
   $(this).data('raphael', {
     circle : c
   })

}

But then I'd like to be able to update elements like this:

$("div").draw({
  type: 'update',
  radius: '20',
  color: '#fff'
});

I can "rescue" the object doing $(this).data().raphael.circle, but then it refuses to animate, I know it's a raphael object because it even has the animate proto , but it yields a Uncaught TypeError: Cannot read property '0' of undefined).


I tried out your code, made some modifications, and $(this).data().raphael.circle does animate. This is what I did (I know it's not exactly the same as yours, but gives the gist)

   $.fn.draw = function( options ) { 
  //settings/options stuff

       if(options.type === 'draw') {
         var width = $(this).width();
         var height = $(this).height();
         var widget = Raphael($(this)[0], width, height);
         var c = widget.circle(100, 100, 50);

         //saving the raphael reference in the element itself
         $(this).data('raphael', {
             circle : c
         });
//$(this).data().raphael.circle.animate() does not work here

        }

        else if(options.type === 'update') {
            $(this).data().raphael.circle.animate({cx: 200, cy: 200});
            //But this works here
        }

}

In this case, referencing the element with $(this).data().raphael.circle does work, but only in the else if. I'm not sure why.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜