2011-09-25 22 views
2

我正在編寫一個插件,它在調用時會顯示一個小幫手。它應該像這樣啓動:

$(el).santasLittleHelper([options]) 

插件,然後有一些「事件」一樣,jQuery UI的有,他們應該被觸發這樣的:

$(el).santasLittleHelper('evetnName', [options]) 

我有一個原型工作,但我對結構的未來問題有幾點擔憂。當我繼續研究它時,氾濫內存或者遇到有變量和函數範圍的其他問題。這裏是一個輪廓:

(function($) { 

$.fn.santasLittleHelper = function(p1, p2) { 

    return this.each(function() { 
     var o = { 
      showSpeed: 50, 
      hideSpeed: 50, 
      duration: 5000, 
      delay: 0 
     } 
     var el = $(this); 
     function init() { 
      console.log('init 1'); 
     } 
     var events = { 
      show: function(opt) {}, 
      hide: function(opt) {}, 
      pulse: function(opt) {} 
     } 
     if(p1 == undefined) {//This is obviously the init call 
      init(); 
     } 
     if(typeof(p1) == 'object') { 
      //Correctly added parameters would then mean that p1 is options 
      //and is the only parameter added so we store the options and init 
      $.extend(o, p1); 
      init(); 
     } 
     if(typeof(p1) == 'string') { 
      //This is a call to an "event". 
      //call the "event" function and supply possible options as arg 
      events[p1](p2); 
     }    
}); 
} 

})(jQuery); 

選項可以爲每個事件調用來提供,但應在該情況下,只有在該事件可用的功能範圍。這是因爲我可能希望幫助者通過在init調用中提供選項來從我創建的心理盒中完成某些操作。

由於聲明變量在代碼的開頭,每次調用$(el).santasLittleHelper('event')時,這種方法是否會填滿內存?

我認爲它看起來很乾淨和可以理解,但是可以改進嗎?

+0

請注意代碼如下:'var init = function init(){...}'。更安全(由於奇怪的瀏覽器錯誤)只需使用'function init(){...}',反正幾乎完全一樣。 – Pointy

+0

是的。我編輯了這篇文章。只有我是對的,該功能仍然在插件範圍內? – Anders

+0

是的,它具有與'var'聲明幾乎完全相同的效果;事實上我會說,如果它導致了一個問題,那可能意味着其他的東西是錯的:-)在你的情況下,它看起來很好。 – Pointy

回答

0

根據練習here,在我看來,你做的是對的,但我會嘗試如果可能使o和事件獨立於每個(如果需要重載,則將其聲明爲可選參數)使用在每個外部聲明的唯一聲明?)

+0

好點!我會考慮的。我是否理解你正確的,如果調用事件看起來像這樣:events [p1](o,p2)和函數簽名是函數(defOptions,tempOptions)? – Anders

+0

是的,你在裏面檢查tempOptions == null,然後用「默認值」替換tempOptions,默認值是通過引用使用的,所以你不需要泛洪內存 –