我正在创建一个 jQuery 插件,并希望提供几个扩展以使解决方案更加模块化。我想我有正确的语法来执行扩展,但我似乎无法调用我的扩展中的任何方法。我只包含了代码部分以尝试简短,但如果需要,我可以提供更多。任何帮助深表感谢!
我将http://jqueryboilerplate.com/用于我的主插件,这个 stackoverflow 答案用于添加我的扩展方法:扩展 jQuery 插件的最佳方式
主要的 jQuery 插件
function Plugin( element, options ) {
this.element = element;
// jQuery has an extend method which merges the contents of two or
// more objects, storing the result in the first object. The first object
// is generally empty as we don't want to alter the default options for
// future instances of the plugin
this.options = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
//This line does NOT work
var id = this.showId();
console.log(id);
var toolbar = this.createToolbar(this.options);
$(this.element).append(toolbar);
if(this.options.showPalette)
{
var palette = this.createPalette(this.options);
$(this.element).append(palette);
this.fetchPalette();
}
var canvas = this.createCanvas(this.options);
$(this.element).append(canvas);
}, ....
插件构造函数
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin( this, options ));
}
});
};
扩展方法
var extensionMethods = {
/*
* retrieve the id of the element
* this is some context within the existing plugin
*/
showId: function(){
return this.element[0].id;
}, ....
jQuery 扩展
$.extend(true, $['fn']['workflowEditor'].prototype, extensionMethods);