javascript - 關于jQuery插件開發,defaults 定義了一個對象為空的方法,在外部調用時如何向這個空的方法添加方法
問題描述
這是一個自己寫的一個簡單插件,問題在下面代碼中有注釋
(function($, window, document, undefined) { // 創造一個公共變量來構建一個私有方法 var privateFunction = function() {// 不是很明白這個私有方法要如何使用,具體有什么用,找了一下資料也不是很明白 } var methods = {nTab: function(options) { return this.each(function() {// 關于 data() 有沒有必要用在這里,我理解 data() 函數是用來保存插件默認沒有的參數或方法用的。不知道這樣理解對不對。和我預留一個onSomeEvent 函數來增加一些功能有什么區別?var $this = $(this);var defaults = { tabTitle: ’.product-tab-title li’, tabContent: ’.product-tab-content’, tabTitleState: ’active’, tabContentBlock: ’block’, tabContentNone: ’none’, eventType: ’click’, onSomeEvent: function() {} // 這個為空的方法我預留處理打算以后遇到需要添加功能的時候使用,但怎么弄都不知道具體的使用方法};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);
這是我外部調用時的代碼
$(function(){ $(’.nTab’).userInCommonUseJsPlugin(’nTab’, {// 我想找這里寫一個onSomeEvent: function() {}來增加插件沒有的功能,該如何實現 });})
問題在上述代碼里有注釋,還望大神指教!!!
問題解答
回答1:好久沒寫過jquery插件了,應該是用把外部添加值通過$.extend方法來拓充到內部
回答2:已經找到其中一個答案了,關于回調函數的使用http://learn.jquery.com/plugi...
插件內回調函數寫法
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 );}
外部調用時使用回調函數
$( 'ul.imgs li' ).superGallery({ onImageShow: function() {$( this ).after( '<span>' + $( this ).attr( 'longdesc' ) + '</span>' ); }, // ... other options ...});
