2013-11-29 37 views
0

目前我正在建设使用这个“模板”我的jQuery插件:Abstractize jQuery插件创建

;(function($, window, document){ 

    var defaultOptions = { 
     option1: value1, 
     option2: value2, 
     }; 

    function plugin(el, options){ 

    this.options = $.extend({}, defaultOptions, options); 
    this.el = el; 

    this.__construct(); 
    }; 

    plugin.prototype = { 

    __construct: function(){ 
     // do the plugin stuff, set up events etc. 
    }, 

    __destruct: function(){ 
     $(this.el).removeData('myPlugin'); 
    }, 

    // other plugin functions here... 
    }; 

    $.fn.myPlugin = function(options){ 
    var additionalArguments = Array.prototype.slice.call(arguments, 1); 

    return this.each(function(){ 
     var inst = $.data(this, 'myPlugin'); 

     if(!(inst instanceof plugin)){ 
     var inst = new plugin(this, options); 
     $.data(this, 'myPlugin', inst); 
     return inst; 
     } 

     if(typeof options == 'string'){ 
     inst[options].apply(inst, additionalArguments); 
     } 
    }); 
    }; 

    $(document).ready(function(){ 
    $('.my-plugin').myPlugin(); 
    }); 

})(jQuery, window, document); 

我得到了大部分意见,从https://github.com/jquery-boilerplate/jquery-boilerplate/blob/master/src/jquery.boilerplate.js

所以这个例子并没有什么,它只是插件的“骨干”,正如你可以看到它是相当多的代码....

我可以建立某种插件的创造者功能,可以让我把上面的代码改写成更小的东西:

createPlugin('myPlugin', { 

    defaultOptions: {}, 

    __construct: function() { 
    ... 
    }, 

    __destruct: function() { 
    ... 
    }, 

    somePublicFunction: function(){ 
    ... 
    } 

}); 

但仍然可以使用它像

$('.element').myPlugin(); 

在PHP中我会使用抽象类为这样的事情,但我不知道如何做到这一点在JavaScript ...

回答

1

这是插件的模式:

(function ($){ 

    $.fn.myPlugin = function (options){ 
    // do something or not to do 
    // anyway it will work 
    return(this);//because 'this' will return the input selector 
    }; 

})(jQuery); 

这足够的代码来实现基本功能。

如果您需要一些createjQueryPlugin(name, methods)功能,可以比YES,您可以。只是包装在函数定义的$.fn.myPlugin,但你还是要定义命名空间:

(function ($){  
//... 
})(jQuery); 

最后,你的代码是相同的,但更长和冗余。

+0

实际上想要'this' not'$(this)'' – charlietfl

0

插件可以像您想要的那样简单或复杂。样板模板是一个足够稳固的框架,可以使用它开发一个非常强大的API,包括即时更改选项设置。

与所有的JavaScript代码一样,它们有很多不同的编写插件的风格。你不受任何指导或规则的约束。唯一的绝对规则是返回this,如果你想插件能够链接。之后,样板中的所有内容都是可选的。你在开口和闭口花括号之间放什么可以是你想要的任何适合你的需求或编码风格的东西