2
我正在創建一個jQuery插件,並希望提供若干擴展,以使解決方案更加模塊化。我想我已經得到了正確的語法來執行擴展,但我似乎無法調用我的擴展中的任何方法。我只包含代碼的一部分來嘗試和簡短,但如果需要,我可以提供更多內容。任何幫助深表感謝!在jQuery擴展中調用方法
我使用http://jqueryboilerplate.com/我的主要插件,這個StackOverflow的答案將我的擴展方法:Best Way to Extend a jQuery Plugin
主要的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);
謝謝,與其他一些我認爲我已經得到了一些工作的骨頭。看着jQuery UI的幫助。基本上我只是試圖在不同的文件中分開我的插件,以避免一個巨大的100,000行javascript文件。 – Mark
@Mark應該可行,但不要忘記,您不能在代碼模塊之間共享詞典範圍(「私有」)變量。 – Alnitak