2012-06-28 49 views
1
;(function ($, w, d, config, undefined) { 
$.fn.pluginName = function (options, config) { 
    var pluginName = this; 
    var defaults = { 
     //defaults 
    }; 
    var settings = $.extend({}, defaults, options); 

    var methods = { 
     init : function (settings, options) { 
      //init stuff here 
     } 
    } 
}) 
})(jQuery, window, document) 

// HTML looks like this 
<script> 
$('.item').pluginName({ methods : 'init' }); 
</script> 

我是新來的插件開發和一般的對象,但我試圖在沒有游泳的深度學習。 :)調用一個函數內的函數來初始化

基本上,我想通過調用方法變量中的「init」函數初始化我的插件。我的插件名稱是「pluginName」。

我無法調用「init」fn,因爲它存在於名爲「methods」的變量中。另外,爲了更進一步,我需要收集頁面上的所有「item」類,並在其中設置一個數據變量。在我的初始化函數,我有以下:

return this.each(function(){ 

    var $this  = $(this), 
    data  = $this.data('pluginName'); 

    if (! data) { 
     $(this).data('pluginName', { 
     target : $this 
     }); 

    } 
}).bind(this); 

以上的回報「this.each是不是一個函數」

任何幫助,將不勝感激!非常感謝!!

回答

2

爲了使它所以你不必在方法調用的對象傳遞,我通常使用這種格式:

(function($) { 
    function doSomething() { 
     // Only callable in this plugin's context (I think) 
    } 

    var methods = { 
     init: function (options) { 
      // Do whatever for init! 
      doSomething(); 
     }, 

     anotherMethod: function (options) { 
      // Some other method 
      doSomething(); 
     } 
    }; 

    $.fn.pollServer = function(method) { 
     var args = arguments; 
     var argss = Array.prototype.slice.call(args, 1); 

     return this.each(function() { 
      $this = $(this); 
      if (methods[method]) { 
       methods[method].apply($this, argss); 
      } 
      else if (typeof method === "object" || !method) { 
       methods.init.apply($this, args); 
      } 
      else { 
       $.error("Method " + method + " does not exist on jQuery.pollServer"); 
      } 
     }); 
    }; 
})(jQuery); 

而且你訪問它想:

$("#div").pollServer({}); 
$("#div").pollServer("init", {}); // Same as above line 

$("#div").pollServer("anotherMethod", {}); 

裏面的一切返回this.each()確定調用什麼方法,並將「this」變量設置爲選定的jQuery元素。它還將其他參數傳遞給方法。

希望這會有所幫助!

+0

這是輝煌!謝謝!我將與此合作。我已經寫了一個不同的模式,但你的看起來更合乎邏輯。一旦我實施了你的解決方案,我會再次評論,並讓你知道它的工作原理!非常感謝! – levelafter

+0

沒問題!我在jQuery網站的某個地方發現了類似的東西,但修改了一些以做我想做的事情。這對我很有用,所以我希望它能幫助你!讓我知道如果你需要更多的指導,像這樣 – Ian

+0

好吧,所以我不想開始混亂我的代碼。 init函數工作得很好,謝謝!所以我有兩個新的問題,我想我是金... 首先。 **如何從「init」中調用函數?**記住它在「methods」變量中。 **另外,如何使用「methods」變量中的函數再次調用「pollServer()」**中的函數? 您可以通過參數傳遞給出的任何示例都將得到極大的提升!你已經幫助我LOADS!謝謝! – levelafter