2013-10-05 77 views
1

不能在网上找到一个很好的例子,所以我试图更新一个支持AMD的插件。我在我的精彩插件模板中添加了一些代码,但我不确定这是否正确。支持AMD的jQuery插件

有关添加这一个插件,将是很好的任何信息(我仍然在学习)

所以这是使用AMD支持的好办法?

;(function (factory) { 
    if (typeof define === 'function' && define.amd) { 
     // AMD. Register as an anonymous module. 
     define(['jquery'], factory); 
    } else { 
     // Browser globals 
     factory(jQuery); 
    } 
}(function($, window, document, undefined){ 

    //"use strict"; // jshint ;_; 

    var pluginName = 'coolPlugin'; 

    function Plugin(element, options){ 

     this.obj = $(element); 
     this.o = $.extend({}, $.fn[pluginName].defaults, options); 

     this.init(); 
    }; 

    Plugin.prototype = { 

     init: function(){ 

      var self = this; 

     }, 

     _private: function(param){ 
      var self = this; 
     }, 

     destroy: function(){ 
      $.removeData(this.obj, this.pluginName);   
     } 

    }; 

    $.fn[pluginName] = function(option, param) { 
     return this.each(function() { 
      var $this = $(this); 
      var data = $this.data(pluginName); 
      var options = typeof option == 'object' && option; 
      if (!data){ 
       $this.data(pluginName, (data = new Plugin(this, options))) 
      } 
      if (typeof option == 'string'){ 
       data[option](param); 
      } 
     }); 
    }; 

    $.fn[pluginName].defaults = { 
     option1: 'helloooo' 

    }; 


})(jQuery, window, document)); 

回答

1

有几个方法可以做到这一点,但我会说你的示例代码是美丽的地方上。只有区别我会做,而不是使用init方法只是简单地使用插件构造函数。

如果您想要另一个示例,我在this jquery plugin中使用了AMD。