2011-04-12 52 views
1

如何從插件中檢索API變量。按照Jquery的創作文檔,這裏是插件結構:帶api的jquery插件

(function($){ 

    var methods = { 

     init : function(options) { 

      return this.each(function() { 
       var settings = { 
        'height' : 10, 
        'width' : 10 
       }; 

       if (options) { $.extend(settings, options); } 

       $('<div>', { 
        css : { 
         height : settings.height, 
         width : settings.width, 
        } 
       }).appendTo(this); 
      }); 

     } 

    }; 

    $.fn.myPlugin = function(method) { 

     if (methods[method]) { 
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 
     } else if (typeof method === 'object' || ! method) { 
      return methods.init.apply(this, arguments); 
     } else { 
      $.error('Method ' + method + ' does not exist on jQuery.element'); 
     }  

    }; 

})(jQuery); 

我想能夠做到以下幾點:

var element = $('div').myPlugin(); 
console.log(element.properties); 

在性能,我想有一個返回的高度的功能,我的Div的寬度。我將如何着手在這個設計中創建屬性變量?

感謝

回答

0

你會擺脫...

return this.each(function() { ... }); 

...和你的插件回報的東西,如...

return { 
    'properties': { 
     'width': calculatedWidth, 
     'height': calculatedHeight 
    } 
} 

然而,這樣做會意味着你不能鏈接另一種方法。

+0

謝謝,實際上我有更多的方法在我的插件中。這只是一個例子。理想情況下,我想只有創建元素的init方法,然後我會執行所有其他操作。 'var element = $('div')。myPlugin(); element.destroy(); element.getProperties();' – Sebastien 2011-04-12 10:36:36