2011-04-24 67 views
2

我創建創建拉斐爾的飛行物體一個jQuery插件,讓我們說你做...如何引用動態創建的Raphael畫布?

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

和插件代碼(就像一個例子):

$.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 
    }) 

} 

但然後我想能夠更新內容如下:

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

我可以「拯救」的對象做$(本)。數據()raphael.circle,但隨後拒絕動畫,我。知道我t是raphael對象,因爲它甚至具有動畫效果proto,但它會產生Uncaught TypeError:無法讀取未定義的屬性'0'。

回答

4

我嘗試了你的代碼,做了一些修改,$(this).data()。raphael.circle做了動畫。這是我做過什麼(我知道這是不完全一樣的你,但給人的要點)

$.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 
     } 

} 

在這種情況下,用$(本)。數據()引用的元素。raphael.circle不工作,但只有在其他情況下。我不知道爲什麼。

+0

你是對的,它確實有效。非常感謝你對它進行測試。我已經把它放在這裏,以防其他人使用它。 http://jsfiddle.net/AvgJf/ – Duopixel 2011-04-24 20:32:35