2012-06-28 57 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