如何编写接受回调函数的jQuery插件方法?

问题描述:

我已经阅读了堆栈溢出的几个类似的情况,但没有一个完全像我的。这里是我的jQuery插件的要点:)如何编写接受回调函数的jQuery插件方法?

(function($) { 
    var methods = { 
     init: function() { 
      ... 
      $(this).myPlugin("close"); 
      $(this).myPlugin("open"); 
     }, 
     open: function() { 
      ... 
     }, 
     close: function() { 
      ... 
     } 
    } 
})(jQuery); 

开(闭()方法包括jQuery的效果基本show()和了slideDown()方法,所以我需要能够调用close()方法,然后调用open()方法作为回调。但是,当我尝试this solution我没有运气。

根据记录,这不起作用:

(function ($) { 
    "use strict"; 

    var methods = { 
     init: function() { 
      return this.each(function() { 
       $(this).click(function() { 
        $(this).myPlugin("close", function() { 
         $(this).myPlugin("open"); 
        }); 
       }); 
      }); 
     }, 
     open: function() { 
      return this.each(function() { 
       console.log("open was called"); 

       $(this).children(":hidden").slideDown("slow"); 
      }); 
     }, 
     close: function (callback) { 
      return this.each(function() { 
       console.log("close was called"); 

       $(this).children(":visible").slideUp("slow"); 

       callback.call($(window)); 
      }); 
     } 
    }; 
}(jQuery)); 

上面的代码清楚地表明,在jQuery的幻灯片动画的情况下,在调用open方法之前,脚本的执行不会等待close方法完成。这里的解决方案,我最终决定采用,使用jQuery承诺方法:

(function ($) { 
    "use strict"; 

    var methods = { 
     init: function() { 
      return this.each(function() { 
       $(this).click(function() { 
        $(this).myPlugin("toggle"); 
       }); 
      }); 
     }, 
     toggle: function() { 
      return this.each(function() { 
       var $openBox = $(this).children(":visible"), 
        $closedBox = $(this).children(":hidden"); 

       $openBox.slideUp("fast").promise().done(function() { 
        $closedBox.slideDown("fast"); 
       }); 
      }); 
     } 
    }; 
}(jQuery)); 

(function($) { 
var methods = { 
    init: function() { 
     ... 
     $(this).myPlugin("close",function() { 
      $(this).myPlugin("open"); 
     } 
    }, 
    open: function() { 
     ... 
    }, 
    close: function(options, callback) { 

     callback.call($(window)); 
     ... 
    } 
} 
})(jQuery); 

您可以使用此代码.. 这是调用被作为参数传递的函数(回调)的方式..

+0

感谢您的答复@Paresh Balar,但我得到的错误'遗漏的类型错误:无法调用undefined'的方法“呼吁”上在线''callback.call($(window));' – 2012-03-28 05:58:33

+0

嘿检查这个演示:http://jsfiddle.net/5QZTs/ – 2012-03-28 06:05:11

+0

你基本上是正确的,除了这是处理jQuery的幻灯片动画。看到我上面的答案。 – 2012-06-21 22:29:49