javascript - 關(guān)于jQuery插件開發(fā),defaults 定義了一個(gè)對(duì)象為空的方法,在外部調(diào)用時(shí)如何向這個(gè)空的方法添加方法
問題描述
這是一個(gè)自己寫的一個(gè)簡(jiǎn)單插件,問題在下面代碼中有注釋
(function($, window, document, undefined) { // 創(chuàng)造一個(gè)公共變量來構(gòu)建一個(gè)私有方法 var privateFunction = function() {// 不是很明白這個(gè)私有方法要如何使用,具體有什么用,找了一下資料也不是很明白 } var methods = {nTab: function(options) { return this.each(function() {// 關(guān)于 data() 有沒有必要用在這里,我理解 data() 函數(shù)是用來保存插件默認(rèn)沒有的參數(shù)或方法用的。不知道這樣理解對(duì)不對(duì)。和我預(yù)留一個(gè)onSomeEvent 函數(shù)來增加一些功能有什么區(qū)別?var $this = $(this);var defaults = { tabTitle: ’.product-tab-title li’, tabContent: ’.product-tab-content’, tabTitleState: ’active’, tabContentBlock: ’block’, tabContentNone: ’none’, eventType: ’click’, onSomeEvent: function() {} // 這個(gè)為空的方法我預(yù)留處理打算以后遇到需要添加功能的時(shí)候使用,但怎么弄都不知道具體的使用方法};var settings = $.extend({}, defaults, options);$this.find(settings.tabTitle).on(settings.eventType, function() { index = $(this).index(); $(this).addClass(settings.tabTitleState).siblings().removeClass(settings.tabTitleState); $(settings.tabContent).eq(index).addClass(settings.tabContentBlock).removeClass(settings.tabContentNone).siblings(settings.tabContent).addClass(settings.tabContentNone).removeClass(settings.tabContentBlock);}); });} }; $.fn.userInCommonUseJsPlugin = function() {var method = arguments[0];if(methods[method]) { method = methods[method]; arguments = Array.prototype.slice.call(arguments, 1);} else/* if( typeof(method) == ’object’ || !method ) { method = methods.init;} else */{ $.error( ’Method ’ + method + ’ does not exist on jQuery.pluginName’ ); return this;}return method.apply(this, arguments); }})(jQuery, window, document);
這是我外部調(diào)用時(shí)的代碼
$(function(){ $(’.nTab’).userInCommonUseJsPlugin(’nTab’, {// 我想找這里寫一個(gè)onSomeEvent: function() {}來增加插件沒有的功能,該如何實(shí)現(xiàn) });})
問題在上述代碼里有注釋,還望大神指教!?。?/p>
問題解答
回答1:好久沒寫過jquery插件了,應(yīng)該是用把外部添加值通過$.extend方法來拓充到內(nèi)部
回答2:已經(jīng)找到其中一個(gè)答案了,關(guān)于回調(diào)函數(shù)的使用http://learn.jquery.com/plugi...
插件內(nèi)回調(diào)函數(shù)寫法
var defaults = { // We define an empty anonymous function so that // we don’t need to check its existence before calling it. onImageShow : function() {}, // ... rest of settings ... }; // Later on in the plugin: nextButton.on( 'click', showNextImage ); function showNextImage() { // Returns reference to the next image node var image = getNextImage(); // Stuff to show the image here... // Here’s the callback: settings.onImageShow.call( image );}
外部調(diào)用時(shí)使用回調(diào)函數(shù)
$( 'ul.imgs li' ).superGallery({ onImageShow: function() {$( this ).after( '<span>' + $( this ).attr( 'longdesc' ) + '</span>' ); }, // ... other options ...});
