2011-02-07 26 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