使用类和原型编写jQuery插件 [英] Writing jQuery Plugins Using Classes and Prototypes

查看:70
本文介绍了使用类和原型编写jQuery插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以这种方式(使用类和原型)编写插件是好是坏做法,此代码的缺点是什么?

Is it good or bad practise writing plugins this way(using class and prototypes), what are disadvatages of this code?

function PluginName(jqueryObject, options) {

}
PluginName.prototype = {
    publicMethod:function() {
    },
    _privateMethod:function() {
    }
}

// Initializing 
var myPluginInstance = new PluginName($(".mySelector"), {myOption:1});
myPluginInstance.publicMethod();

推荐答案

请参见有关插件创作的jQuery文档以获得最佳做法:

See the jQuery docs on plugin authoring for best practices:

  • 始终将您的插件包装在(function( $ ){ // plugin goes here })( jQuery );
  • 不要在插件功能的直接作用域中多余地包装此关键字
  • 除非您要从插件返回固有值,否则始终让插件的函数返回this关键字以保持可链接性.
  • 无需花费大量参数,而是将您的插件设置传递到可以扩展到插件默认值的对象文本中.
  • 不要使每个插件具有多个命名空间的jQuery.fn对象杂乱无章.
  • 始终为您的方法,事件和数据命名空间.
  • Always wrap your plugin in (function( $ ){ // plugin goes here })( jQuery );
  • Don't redundantly wrap the this keyword in the immediate scope of your plugin's function
  • Unless you're returning an intrinsic value from your plugin, always have your plugin's function return the this keyword to maintain chainability.
  • Rather than requiring a lengthy amount of arguments, pass your plugin settings in an object literal that can be extended over the plugin's defaults.
  • Don't clutter the jQuery.fn object with more than one namespace per plugin.
  • Always namespace your methods, events and data.
(function( $ ){

  var methods = {
    init : function( options ) { // THIS },
    show : function( ) { // IS   },
    hide : function( ) { // GOOD },
    update : function( content ) { // !!! }
  };

  $.fn.tooltip = function( method ) {

    // Method calling logic
    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.tooltip' );
    }    

  };

})( jQuery );

用法:

$('div').tooltip(); // calls the init method
$('div').tooltip({  // calls the init method
  foo : 'bar'
});
$('div').tooltip('hide'); // calls the hide method
$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update method

默认值和选项示例

(function( $ ){

  $.fn.tooltip = function( options ) {  

    var settings = {
      'location'         : 'top',
      'background-color' : 'blue'
    };

    return this.each(function() {        
      // If options exist, lets merge them
      // with our default settings
      if ( options ) { 
        $.extend( settings, options );
      }

      // Tooltip plugin code here

    });

  };
})( jQuery );

用法:

$('div').tooltip({
  'location' : 'left'
});

这篇关于使用类和原型编写jQuery插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆