2012-07-20 25 views
0

jQuery plugin tutorial中,show(),hide()或update()等其他方法如何訪問在init()中傳遞的選項?在init()中處理它的正確方法是什麼,以便其他方法可以訪問它?JQuery插件教程 - init訪問選項以外的方法如何?

(function($){ 

    var methods = { 
    init : function(options) { // THIS }, 
    show : function() { // IS }, 
    hide : function() { // GOOD }, 
    update : function(content) { // !!! } 
    }; 

    $.fn.tooltip = function(method) { 

    // Method calling logic 
    if (methods[method]) { 
     return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); 
    } else if (typeof method === 'object' || ! method) { 
     return methods.init.apply(this, arguments); 
    } else { 
     $.error('Method ' + method + ' does not exist on jQuery.tooltip'); 
    }  

    }; 

})(jQuery); 

回答

0
在我的插件

我總是使用訪問選項:

this.options 

但是...我使用diferent方法...

(function ($) { 
    $.widget("my.plugin", { 
     options: { 
      op1: "op1" 
     }, 
     _init: function() { 

     }, 
     _create: function() { 

     }, 
     show: function() { 
     } 
    }); 
})(jQuery); 
+0

是不是有什麼特別的用 '部件'?我剛開始嘗試創建一個jQuery插件,並且該結構對我來說似乎是新的。你能解釋爲什麼它的結構是這樣嗎? – arvinsim 2012-07-20 08:49:05

+0

從我所知道的,這是創建jquery-ui插件的方式,所以它必須是一個很好的選擇:)基本上可以節省您的時間併爲您的插件提供基本結構。例如:「方法調用邏輯」已經實現。 以'_'開頭的函數是私有的,不能通過使用$('#xpto')。myplugin('method')調用。 函數如「_create」和「_init」被自動調用。 – V1tOr 2012-07-20 08:52:08

+0

這個解決方案jquery-ui依賴嗎? – arvinsim 2012-07-20 17:31:17

相關問題