2013-05-13 73 views
2

我想在自定义jQuery插件的回调之前和之后添加。 我从来没有尝试过回调。所以请帮助我。jQuery - 在插件的回调之前和之后添加

这是我的插件代码


(function($){ 
    $.fn.OneByOne = function(options){ 

     var defaults = { 
      startDelay:5,   
      duration: 1000, 
      nextDelay: 700 
     }; 

     var options = $.extend(defaults, options); 
     var delay = options.startDelay; 
     return this.each(function(){ 

      var o = options; 
      var obj = $(this);     
      var a = $('a', obj);   

      obj.css({'margin-top':'100px','opacity': '0'});   
      obj.delay(delay).fadeIn().animate({opacity: 1,'margin-top':'0'}, o.duration); 
      delay += o.nextDelay; 


     }); 


    }; 
})(jQuery); 

前和后的回调


我想打电话给before回调到哪里调用之前:

obj.css({'margin-top':'100px','opacity': '0'});   
    obj.delay(delay).fadeIn().animate({opacity: 1,'margin-top':'0'}, o.duration); 
    delay += o.nextDelay; 

并且想要拨打after回拨刚才上面的代码。

我需要回调


我想用我的回调

http://ricostacruz.com/jquery.transit/

过渡。

请同时告诉我如何在调用插件时使用回调函数。

谢谢。

+1

我知道你希望插件接受用户的回调定义之前和之后吗? – sixFingers 2013-05-13 11:28:23

+0

http://stackoverflow.com/questions/2534436/jquery-plugin-adding-callback-functionality – worenga 2013-05-13 11:29:09

+0

@sixFingers,是回调定义是由用户给出 – user007 2013-05-13 11:31:50

回答

2
  1. 让用户在回调之前和之后通过。 里面您的默认值,指定一个默认的回调函数:

    在$插件
    var defaults = { 
        startDelay:5,   
        duration: 1000, 
        nextDelay: 700 
    }; 
    
    // Test if user passed valid functions 
    options.before = typeof options.before == 'function' ? options.before || function(){}; 
    options.after = typeof options.after == 'function' ? options.after || function(){}; 
    

    选项在哈希获得通过,从而使用户能够通过他们的

    $("…").OneByOne({…, before: function() {}, after: function() {}); 
    
  2. 在你的插件代码,你有勾给他们,让他们得到所谓的(默认的值,或任何用户定义的回调):

    // Before is simply called before starting animation 
    // Use call or apply on the callback passing any wanted argument. 
    before.call(this, obj); 
    // After callback is passed directly to animate function and gets called on animation complete. 
    obj.delay(delay).fadeIn().animate({opacity: 1,'margin-top':'0'}, o.duration, after); 
    
  3. 任何参数为“前”回调会在回调之前用户定义的可用;回调后将调用obj上下文,所以在回调后定义的任何用户,$(this)是你的obj的

+0

我正要回答这个问题,直到我看到你的问题。对,但我最好测试一下,如果用户输入了前后参数作为函数(使用typeof或jquery isFunction())以执行一些后备机制,否则。 – Arman 2013-05-13 12:20:00

+0

你是对的,编辑。 – sixFingers 2013-05-13 12:20:48

+1

或者也许没关系,因为许多其他人都做得很好,即使是[jquery book](http://www.manning.com/bibeault/)的示例代码之一:) – Arman 2013-05-13 12:30:37