2013-11-29 38 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,如果你想插件能夠鏈接。之後,樣板中的所有內容都是可選的。你在開口和閉口花括號之間放什麼可以是你想要的任何適合你的需求或編碼風格的東西