2011-02-07 31 views
3

我已經開始寫jQuery插件,我希望能夠:我寫jQuery插件的方式是否正確?

  1. 初始化它,當我這樣稱呼它$('selector').sitemap(options);
  2. 使用一些成員(如「裝載機」,「視口」)的功能在插件

對於第一問題:我已經在我寫的初始化(初始化函數)或有更正確的/優雅的方式來做到這一點的方式做正確嗎?

關於第二個問題:爲了使用會員像「裝載機」,「視口」我寫的所有功能,在地圖對象。我做對了嗎?還是有更正確/優雅的方式來做到這一點?

(function ($) { 
    $.extend($.fn, { 
     sitemap: function (options) { 
      //check if applied on valid DIV element 
      var canvas = this; 
      if (!canvas.is('div')) return; 

      var viewPort = null; 
      var loader = $('<p id="initLoader">Loading...</p>'); 

      init(); 
      loadMap(); 

      function init() { 
       //create viewPort div 

       setCanvas(); 
      } 
      function setCanvas() { 
         //set height and width 
      } 
      function loadMap() { 
       viewPort.prepend(loader);      
       buildMap($.parseJSON('{"pages":[]}')); 
      } 
      function buildMap(map){ 
       //... 
      }   
})(jQuery); 

回答

2

爲您重構您的代碼。

將網站地圖功能移到閉合範圍中。將所有操作包裝到構造函數中。

您創建一個新的站點地圖對象,並在站點地圖構造函數中調用原型的方法鏈。

至於1. & 2.我認爲使用一個對象來存儲您的站點地圖的狀態更優雅,然後將所有內容轉儲到jQuery調用的函數中。這分開您的「Sitemap」對象的操縱和通過jquery操縱dom。

您現在可以使用任何面向對象的OO技術。就像創建一個Map函數並委派loadMap創建一個new Map並且在其上調用map.getHTML

(function($) { 

    // to be called when $(selector).sitemap is called. 

    function sitemap(options) { 
     // store the canvas 
     var canvas = this; 
     if (canvas.is("div")) { 
      // if its a div then create a new canvas object. 
      // Ideally the object will set event handlers and should handle 
      // any changes through dom events so you dont have to manually 
      // call any methods on it 
      canvas = new Sitemap(canvas); 
     } 
     // return this so you can chain .sitemap 
     return this; 
    } 

    // Constructor function takes the div 

    function Sitemap(canvas) { 
     // store them as variables on the sitemap object 
     this.canvas = canvas; 
     this.viewport = null; 

     // init & load the map. 
     this.init(); 
    } 

    // All sitemap objects have these methods defined on them 
    Sitemap.prototype.init = function() { 
     //create viewport div 
     //set height and width 
     this.loadmap(); 
    }; 

    Sitemap.prototype.loadMap = function() { 
     var loader = $('<p id="initLoader">Loading...</p>'); 
     this.viewPort.prepend(loader); 
     // create a new map object 
     this.map = new Map(json); 
    }; 

    function Map(json) { 
     //... 
    } 

    Map.prototype.addToContainer = function(container) { 
     //... 
    }; 


    $.extend($.fn, { 
     sitemap: sitemap 
    }); 

})(jQuery); 
+0

你是否認爲這是明智的,有一個'站點地圖()`和`一個站點地圖()`函數? – ZeissS 2011-02-07 15:41:32