2012-01-07 42 views
0

我正在研究一种用于jQuery插件的全功能基础框架。我基于jQuery插件/创作示例发现here的结构。带有方法和回调的jQuery插件

这里的结构的进一步简化版本,我的建筑:

(function($){ 
    var methods = { 
    init : function(options) { 
     var defaults = { 
      // place default settings for plugin here 
     } 

     var options = $.extend(defaults, options); 

     return this.each(function(){ 
      var $this = $(this), 
       data = $this.data('PLUGINNAME'); 

      if (! data) { 
      // do more setup stuff here 
      } 
     }); 
    }, 

    destroy : function() { 
     return this.each(function(){ 
     // do stuff to destroy any function binding 
     }) 
    }, 

    update : function(content) { 
     return this.each(function() { 
      //do your update stuff here 
     }) 
    } 
    }; 

    $.fn.PLUGINNAME = function(method) { 
    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.PLUGINNAME'); 
    }  
    }; 
})(jQuery); 

,我试图现在要弄清楚的是如何把一个回调函数添加到该插件调用。我知道,我需要另一个参数是这样的:

$.fn.PLUGINNAME = function(method, callback) { 

,但我不知道如何去实现一个基于什么我现在有。

+0

这个回调应该做什么,它的签名是什么? – 2012-01-07 17:57:44

+0

回调应该做什么并不重要。也许它只是一个函数,需要等到插件运行某个脚本(如getJSON调用)才能处理页面上的某个元素。 – 2012-01-07 18:28:37

回答

1

要调用回调函数,可以使用.call方法。

init : function(options, callback) { 
    callback.call(this, options); 

在这个例子中,我传递了选项,但是你可以传递你需要的任何东西。

+0

但是,如何使用插件的可链接性的思想工作,使用'return this.each(function(){'return允许? – 2012-01-07 18:26:30

+0

回调不会影响“this”,所以只要您返回“this “它会保持可链接的 你可以看看一些jQuery的默认函数,它们允许回调来查看它们传入的参数。 – 2012-01-07 18:37:29

+0

那么我的update方法看起来像这样吗?'update:function(options,callback){ return this.each(function(){ callback.call(this,options); }) }'是否有任何更改插件本身? – 2012-01-07 18:50:04